Coverage Report

Created: 2024-08-09 01:22

/src/DLXEmu/external/imgui/imgui.cpp
Line
Count
Source (jump to first uncovered line)
1
// dear imgui, v1.91.1 WIP
2
// (main code and documentation)
3
4
// Help:
5
// - See links below.
6
// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that.
7
// - Read top of imgui.cpp for more details, links and comments.
8
9
// Resources:
10
// - FAQ ........................ https://dearimgui.com/faq (in repository as docs/FAQ.md)
11
// - Homepage ................... https://github.com/ocornut/imgui
12
// - Releases & changelog ....... https://github.com/ocornut/imgui/releases
13
// - Gallery .................... https://github.com/ocornut/imgui/issues/7503 (please post your screenshots/video there!)
14
// - Wiki ....................... https://github.com/ocornut/imgui/wiki (lots of good stuff there)
15
//   - Getting Started            https://github.com/ocornut/imgui/wiki/Getting-Started (how to integrate in an existing app by adding ~25 lines of code)
16
//   - Third-party Extensions     https://github.com/ocornut/imgui/wiki/Useful-Extensions (ImPlot & many more)
17
//   - Bindings/Backends          https://github.com/ocornut/imgui/wiki/Bindings (language bindings, backends for various tech/engines)
18
//   - Glossary                   https://github.com/ocornut/imgui/wiki/Glossary
19
//   - Debug Tools                https://github.com/ocornut/imgui/wiki/Debug-Tools
20
//   - Software using Dear ImGui  https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui
21
// - Issues & support ........... https://github.com/ocornut/imgui/issues
22
// - Test Engine & Automation ... https://github.com/ocornut/imgui_test_engine (test suite, test engine to automate your apps)
23
24
// For first-time users having issues compiling/linking/running/loading fonts:
25
// please post in https://github.com/ocornut/imgui/discussions if you cannot find a solution in resources above.
26
// Everything else should be asked in 'Issues'! We are building a database of cross-linked knowledge there.
27
28
// Copyright (c) 2014-2024 Omar Cornut
29
// Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
30
// See LICENSE.txt for copyright and licensing details (standard MIT License).
31
// This library is free but needs your support to sustain development and maintenance.
32
// Businesses: you can support continued development via B2B invoiced technical support, maintenance and sponsoring contracts.
33
// PLEASE reach out at omar AT dearimgui DOT com. See https://github.com/ocornut/imgui/wiki/Funding
34
// Businesses: you can also purchase licenses for the Dear ImGui Automation/Test Engine.
35
36
// It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library.
37
// Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without
38
// modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't
39
// come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you
40
// to a better solution or official support for them.
41
42
/*
43
44
Index of this file:
45
46
DOCUMENTATION
47
48
- MISSION STATEMENT
49
- CONTROLS GUIDE
50
- PROGRAMMER GUIDE
51
  - READ FIRST
52
  - HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
53
  - GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
54
  - HOW A SIMPLE APPLICATION MAY LOOK LIKE
55
  - HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
56
- API BREAKING CHANGES (read me when you update!)
57
- FREQUENTLY ASKED QUESTIONS (FAQ)
58
  - Read all answers online: https://www.dearimgui.com/faq, or in docs/FAQ.md (with a Markdown viewer)
59
60
CODE
61
(search for "[SECTION]" in the code to find them)
62
63
// [SECTION] INCLUDES
64
// [SECTION] FORWARD DECLARATIONS
65
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
66
// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
67
// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
68
// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
69
// [SECTION] MISC HELPERS/UTILITIES (File functions)
70
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
71
// [SECTION] MISC HELPERS/UTILITIES (Color functions)
72
// [SECTION] ImGuiStorage
73
// [SECTION] ImGuiTextFilter
74
// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
75
// [SECTION] ImGuiListClipper
76
// [SECTION] STYLING
77
// [SECTION] RENDER HELPERS
78
// [SECTION] INITIALIZATION, SHUTDOWN
79
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
80
// [SECTION] ID STACK
81
// [SECTION] INPUTS
82
// [SECTION] ERROR CHECKING
83
// [SECTION] ITEM SUBMISSION
84
// [SECTION] LAYOUT
85
// [SECTION] SCROLLING
86
// [SECTION] TOOLTIPS
87
// [SECTION] POPUPS
88
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
89
// [SECTION] DRAG AND DROP
90
// [SECTION] LOGGING/CAPTURING
91
// [SECTION] SETTINGS
92
// [SECTION] LOCALIZATION
93
// [SECTION] VIEWPORTS, PLATFORM WINDOWS
94
// [SECTION] DOCKING
95
// [SECTION] PLATFORM DEPENDENT HELPERS
96
// [SECTION] METRICS/DEBUGGER WINDOW
97
// [SECTION] DEBUG LOG WINDOW
98
// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, ID STACK TOOL)
99
100
*/
101
102
//-----------------------------------------------------------------------------
103
// DOCUMENTATION
104
//-----------------------------------------------------------------------------
105
106
/*
107
108
 MISSION STATEMENT
109
 =================
110
111
 - Easy to use to create code-driven and data-driven tools.
112
 - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools.
113
 - Easy to hack and improve.
114
 - Minimize setup and maintenance.
115
 - Minimize state storage on user side.
116
 - Minimize state synchronization.
117
 - Portable, minimize dependencies, run on target (consoles, phones, etc.).
118
 - Efficient runtime and memory consumption.
119
120
 Designed primarily for developers and content-creators, not the typical end-user!
121
 Some of the current weaknesses (which we aim to address in the future) includes:
122
123
 - Doesn't look fancy.
124
 - Limited layout features, intricate layouts are typically crafted in code.
125
126
127
 CONTROLS GUIDE
128
 ==============
129
130
 - MOUSE CONTROLS
131
   - Mouse wheel:                   Scroll vertically.
132
   - SHIFT+Mouse wheel:             Scroll horizontally.
133
   - Click [X]:                     Close a window, available when 'bool* p_open' is passed to ImGui::Begin().
134
   - Click ^, Double-Click title:   Collapse window.
135
   - Drag on corner/border:         Resize window (double-click to auto fit window to its contents).
136
   - Drag on any empty space:       Move window (unless io.ConfigWindowsMoveFromTitleBarOnly = true).
137
   - Left-click outside popup:      Close popup stack (right-click over underlying popup: Partially close popup stack).
138
139
 - TEXT EDITOR
140
   - Hold SHIFT or Drag Mouse:      Select text.
141
   - CTRL+Left/Right:               Word jump.
142
   - CTRL+Shift+Left/Right:         Select words.
143
   - CTRL+A or Double-Click:        Select All.
144
   - CTRL+X, CTRL+C, CTRL+V:        Use OS clipboard.
145
   - CTRL+Z, CTRL+Y:                Undo, Redo.
146
   - ESCAPE:                        Revert text to its original value.
147
   - On OSX, controls are automatically adjusted to match standard OSX text editing 2ts and behaviors.
148
149
 - KEYBOARD CONTROLS
150
   - Basic:
151
     - Tab, SHIFT+Tab               Cycle through text editable fields.
152
     - CTRL+Tab, CTRL+Shift+Tab     Cycle through windows.
153
     - CTRL+Click                   Input text into a Slider or Drag widget.
154
   - Extended features with `io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard`:
155
     - Tab, SHIFT+Tab:              Cycle through every items.
156
     - Arrow keys                   Move through items using directional navigation. Tweak value.
157
     - Arrow keys + Alt, Shift      Tweak slower, tweak faster (when using arrow keys).
158
     - Enter                        Activate item (prefer text input when possible).
159
     - Space                        Activate item (prefer tweaking with arrows when possible).
160
     - Escape                       Deactivate item, leave child window, close popup.
161
     - Page Up, Page Down           Previous page, next page.
162
     - Home, End                    Scroll to top, scroll to bottom.
163
     - Alt                          Toggle between scrolling layer and menu layer.
164
     - CTRL+Tab then Ctrl+Arrows    Move window. Hold SHIFT to resize instead of moving.
165
   - Output when ImGuiConfigFlags_NavEnableKeyboard set,
166
     - io.WantCaptureKeyboard flag is set when keyboard is claimed.
167
     - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set.
168
     - io.NavVisible: true when the navigation cursor is visible (usually goes to back false when mouse is used).
169
170
 - GAMEPAD CONTROLS
171
   - Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
172
   - Particularly useful to use Dear ImGui on a console system (e.g. PlayStation, Switch, Xbox) without a mouse!
173
   - Download controller mapping PNG/PSD at http://dearimgui.com/controls_sheets
174
   - Backend support: backend needs to:
175
      - Set 'io.BackendFlags |= ImGuiBackendFlags_HasGamepad' + call io.AddKeyEvent/AddKeyAnalogEvent() with ImGuiKey_Gamepad_XXX keys.
176
      - For analog values (0.0f to 1.0f), backend is responsible to handling a dead-zone and rescaling inputs accordingly.
177
        Backend code will probably need to transform your raw inputs (such as e.g. remapping your 0.2..0.9 raw input range to 0.0..1.0 imgui range, etc.).
178
      - BEFORE 1.87, BACKENDS USED TO WRITE TO io.NavInputs[]. This is now obsolete. Please call io functions instead!
179
   - If you need to share inputs between your game and the Dear ImGui interface, the easiest approach is to go all-or-nothing,
180
     with a buttons combo to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved.
181
182
 - REMOTE INPUTS SHARING & MOUSE EMULATION
183
   - PS4/PS5 users: Consider emulating a mouse cursor with DualShock touch pad or a spare analog stick as a mouse-emulation fallback.
184
   - Consoles/Tablet/Phone users: Consider using a Synergy 1.x server (on your PC) + run examples/libs/synergy/uSynergy.c (on your console/tablet/phone app)
185
     in order to share your PC mouse/keyboard.
186
   - See https://github.com/ocornut/imgui/wiki/Useful-Extensions#remoting for other remoting solutions.
187
   - On a TV/console system where readability may be lower or mouse inputs may be awkward, you may want to set the ImGuiConfigFlags_NavEnableSetMousePos flag.
188
     Enabling ImGuiConfigFlags_NavEnableSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs Dear ImGui to move your mouse cursor along with navigation movements.
189
     When enabled, the NewFrame() function may alter 'io.MousePos' and set 'io.WantSetMousePos' to notify you that it wants the mouse cursor to be moved.
190
     When that happens your backend NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the backends in examples/ do that.
191
     (If you set the NavEnableSetMousePos flag but don't honor 'io.WantSetMousePos' properly, Dear ImGui will misbehave as it will see your mouse moving back & forth!)
192
     (In a setup when you may not have easy control over the mouse cursor, e.g. uSynergy.c doesn't expose moving remote mouse cursor, you may want
193
     to set a boolean to ignore your other external mouse positions until the external source is moved again.)
194
195
196
 PROGRAMMER GUIDE
197
 ================
198
199
 READ FIRST
200
 ----------
201
 - Remember to check the wonderful Wiki (https://github.com/ocornut/imgui/wiki)
202
 - Your code creates the UI every frame of your application loop, if your code doesn't run the UI is gone!
203
   The UI can be highly dynamic, there are no construction or destruction steps, less superfluous
204
   data retention on your side, less state duplication, less state synchronization, fewer bugs.
205
 - Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
206
   Or browse https://pthom.github.io/imgui_manual_online/manual/imgui_manual.html for interactive web version.
207
 - The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build.
208
 - Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori).
209
   You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links in Wiki.
210
 - Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances.
211
   For every application frame, your UI code will be called only once. This is in contrast to e.g. Unity's implementation of an IMGUI,
212
   where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches.
213
 - Our origin is on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right.
214
 - Please make sure you have asserts enabled (IM_ASSERT redirects to assert() by default, but can be redirected).
215
   If you get an assert, read the messages and comments around the assert.
216
 - This codebase aims to be highly optimized:
217
   - A typical idle frame should never call malloc/free.
218
   - We rely on a maximum of constant-time or O(N) algorithms. Limiting searches/scans as much as possible.
219
   - We put particular energy in making sure performances are decent with typical "Debug" build settings as well.
220
     Which mean we tend to avoid over-relying on "zero-cost abstraction" as they aren't zero-cost at all.
221
 - This codebase aims to be both highly opinionated and highly flexible:
222
   - This code works because of the things it choose to solve or not solve.
223
   - C++: this is a pragmatic C-ish codebase: we don't use fancy C++ features, we don't include C++ headers,
224
     and ImGui:: is a namespace. We rarely use member functions (and when we did, I am mostly regretting it now).
225
     This is to increase compatibility, increase maintainability and facilitate use from other languages.
226
   - C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types.
227
     See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that.
228
     We can can optionally export math operators for ImVec2/ImVec4 using IMGUI_DEFINE_MATH_OPERATORS, which we use internally.
229
   - C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction
230
     (so don't use ImVector in your code or at our own risk!).
231
   - Building: We don't use nor mandate a build system for the main library.
232
     This is in an effort to ensure that it works in the real world aka with any esoteric build setup.
233
     This is also because providing a build system for the main library would be of little-value.
234
     The build problems are almost never coming from the main library but from specific backends.
235
236
237
 HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
238
 ----------------------------------------------
239
 - Update submodule or copy/overwrite every file.
240
 - About imconfig.h:
241
   - You may modify your copy of imconfig.h, in this case don't overwrite it.
242
   - or you may locally branch to modify imconfig.h and merge/rebase latest.
243
   - or you may '#define IMGUI_USER_CONFIG "my_config_file.h"' globally from your build system to
244
     specify a custom path for your imconfig.h file and instead not have to modify the default one.
245
246
 - Overwrite all the sources files except for imconfig.h (if you have modified your copy of imconfig.h)
247
 - Or maintain your own branch where you have imconfig.h modified as a top-most commit which you can regularly rebase over "master".
248
 - You can also use '#define IMGUI_USER_CONFIG "my_config_file.h" to redirect configuration to your own file.
249
 - Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
250
   If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed
251
   from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will
252
   likely be a comment about it. Please report any issue to the GitHub page!
253
 - To find out usage of old API, you can add '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' in your configuration file.
254
 - Try to keep your copy of Dear ImGui reasonably up to date!
255
256
257
 GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
258
 ---------------------------------------------------------------
259
 - See https://github.com/ocornut/imgui/wiki/Getting-Started.
260
 - Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library.
261
 - In the majority of cases you should be able to use unmodified backends files available in the backends/ folder.
262
 - Add the Dear ImGui source files + selected backend source files to your projects or using your preferred build system.
263
   It is recommended you build and statically link the .cpp files as part of your project and NOT as a shared library (DLL).
264
 - You can later customize the imconfig.h file to tweak some compile-time behavior, such as integrating Dear ImGui types with your own maths types.
265
 - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
266
 - Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide.
267
   Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render"
268
   phases of your own application. All rendering information is stored into command-lists that you will retrieve after calling ImGui::Render().
269
 - Refer to the backends and demo applications in the examples/ folder for instruction on how to setup your code.
270
 - If you are running over a standard OS with a common graphics API, you should be able to use unmodified imgui_impl_*** files from the examples/ folder.
271
272
273
 HOW A SIMPLE APPLICATION MAY LOOK LIKE
274
 --------------------------------------
275
 EXHIBIT 1: USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.cpp files from the backends/ folder).
276
 The sub-folders in examples/ contain examples applications following this structure.
277
278
     // Application init: create a dear imgui context, setup some options, load fonts
279
     ImGui::CreateContext();
280
     ImGuiIO& io = ImGui::GetIO();
281
     // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
282
     // TODO: Fill optional fields of the io structure later.
283
     // TODO: Load TTF/OTF fonts if you don't want to use the default font.
284
285
     // Initialize helper Platform and Renderer backends (here we are using imgui_impl_win32.cpp and imgui_impl_dx11.cpp)
286
     ImGui_ImplWin32_Init(hwnd);
287
     ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
288
289
     // Application main loop
290
     while (true)
291
     {
292
         // Feed inputs to dear imgui, start new frame
293
         ImGui_ImplDX11_NewFrame();
294
         ImGui_ImplWin32_NewFrame();
295
         ImGui::NewFrame();
296
297
         // Any application code here
298
         ImGui::Text("Hello, world!");
299
300
         // Render dear imgui into screen
301
         ImGui::Render();
302
         ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
303
         g_pSwapChain->Present(1, 0);
304
     }
305
306
     // Shutdown
307
     ImGui_ImplDX11_Shutdown();
308
     ImGui_ImplWin32_Shutdown();
309
     ImGui::DestroyContext();
310
311
 EXHIBIT 2: IMPLEMENTING CUSTOM BACKEND / CUSTOM ENGINE
312
313
     // Application init: create a dear imgui context, setup some options, load fonts
314
     ImGui::CreateContext();
315
     ImGuiIO& io = ImGui::GetIO();
316
     // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
317
     // TODO: Fill optional fields of the io structure later.
318
     // TODO: Load TTF/OTF fonts if you don't want to use the default font.
319
320
     // Build and load the texture atlas into a texture
321
     // (In the examples/ app this is usually done within the ImGui_ImplXXX_Init() function from one of the demo Renderer)
322
     int width, height;
323
     unsigned char* pixels = nullptr;
324
     io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
325
326
     // At this point you've got the texture data and you need to upload that to your graphic system:
327
     // After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'.
328
     // This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ for details about ImTextureID.
329
     MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA32)
330
     io.Fonts->SetTexID((void*)texture);
331
332
     // Application main loop
333
     while (true)
334
     {
335
        // Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc.
336
        // (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform Backends)
337
        io.DeltaTime = 1.0f/60.0f;              // set the time elapsed since the previous frame (in seconds)
338
        io.DisplaySize.x = 1920.0f;             // set the current display width
339
        io.DisplaySize.y = 1280.0f;             // set the current display height here
340
        io.AddMousePosEvent(mouse_x, mouse_y);  // update mouse position
341
        io.AddMouseButtonEvent(0, mouse_b[0]);  // update mouse button states
342
        io.AddMouseButtonEvent(1, mouse_b[1]);  // update mouse button states
343
344
        // Call NewFrame(), after this point you can use ImGui::* functions anytime
345
        // (So you want to try calling NewFrame() as early as you can in your main loop to be able to use Dear ImGui everywhere)
346
        ImGui::NewFrame();
347
348
        // Most of your application code here
349
        ImGui::Text("Hello, world!");
350
        MyGameUpdate(); // may use any Dear ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
351
        MyGameRender(); // may use any Dear ImGui functions as well!
352
353
        // Render dear imgui, swap buffers
354
        // (You want to try calling EndFrame/Render as late as you can, to be able to use Dear ImGui in your own game rendering code)
355
        ImGui::EndFrame();
356
        ImGui::Render();
357
        ImDrawData* draw_data = ImGui::GetDrawData();
358
        MyImGuiRenderFunction(draw_data);
359
        SwapBuffers();
360
     }
361
362
     // Shutdown
363
     ImGui::DestroyContext();
364
365
 To decide whether to dispatch mouse/keyboard inputs to Dear ImGui to the rest of your application,
366
 you should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
367
 Please read the FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" about this.
368
369
370
 HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
371
 ---------------------------------------------
372
 The backends in impl_impl_XXX.cpp files contain many working implementations of a rendering function.
373
374
    void MyImGuiRenderFunction(ImDrawData* draw_data)
375
    {
376
       // TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
377
       // TODO: Setup texture sampling state: sample with bilinear filtering (NOT point/nearest filtering). Use 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines;' to allow point/nearest filtering.
378
       // TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
379
       // TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
380
       // TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color.
381
       ImVec2 clip_off = draw_data->DisplayPos;
382
       for (int n = 0; n < draw_data->CmdListsCount; n++)
383
       {
384
          const ImDrawList* cmd_list = draw_data->CmdLists[n];
385
          const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data;  // vertex buffer generated by Dear ImGui
386
          const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data;   // index buffer generated by Dear ImGui
387
          for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
388
          {
389
             const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
390
             if (pcmd->UserCallback)
391
             {
392
                 pcmd->UserCallback(cmd_list, pcmd);
393
             }
394
             else
395
             {
396
                 // Project scissor/clipping rectangles into framebuffer space
397
                 ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y);
398
                 ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y);
399
                 if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
400
                     continue;
401
402
                 // We are using scissoring to clip some objects. All low-level graphics API should support it.
403
                 // - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches
404
                 //   (some elements visible outside their bounds) but you can fix that once everything else works!
405
                 // - Clipping coordinates are provided in imgui coordinates space:
406
                 //   - For a given viewport, draw_data->DisplayPos == viewport->Pos and draw_data->DisplaySize == viewport->Size
407
                 //   - In a single viewport application, draw_data->DisplayPos == (0,0) and draw_data->DisplaySize == io.DisplaySize, but always use GetMainViewport()->Pos/Size instead of hardcoding those values.
408
                 //   - In the interest of supporting multi-viewport applications (see 'docking' branch on github),
409
                 //     always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space.
410
                 // - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min)
411
                 MyEngineSetScissor(clip_min.x, clip_min.y, clip_max.x, clip_max.y);
412
413
                 // The texture for the draw call is specified by pcmd->GetTexID().
414
                 // The vast majority of draw calls will use the Dear ImGui texture atlas, which value you have set yourself during initialization.
415
                 MyEngineBindTexture((MyTexture*)pcmd->GetTexID());
416
417
                 // Render 'pcmd->ElemCount/3' indexed triangles.
418
                 // By default the indices ImDrawIdx are 16-bit, you can change them to 32-bit in imconfig.h if your engine doesn't support 16-bit indices.
419
                 MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer + pcmd->IdxOffset, vtx_buffer, pcmd->VtxOffset);
420
             }
421
          }
422
       }
423
    }
424
425
426
 API BREAKING CHANGES
427
 ====================
428
429
 Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix.
430
 Below is a change-log of API breaking changes only. If you are using one of the functions listed, expect to have to fix some code.
431
 When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files.
432
 You can read releases logs https://github.com/ocornut/imgui/releases for more details.
433
434
(Docking/Viewport Branch)
435
 - 2024/XX/XX (1.XXXX) - when multi-viewports are enabled, all positions will be in your natural OS coordinates space. It means that:
436
                          - reference to hard-coded positions such as in SetNextWindowPos(ImVec2(0,0)) are probably not what you want anymore.
437
                            you may use GetMainViewport()->Pos to offset hard-coded positions, e.g. SetNextWindowPos(GetMainViewport()->Pos)
438
                          - likewise io.MousePos and GetMousePos() will use OS coordinates.
439
                            If you query mouse positions to interact with non-imgui coordinates you will need to offset them, e.g. subtract GetWindowViewport()->Pos.
440
441
 - 2024/07/25 (1.91.0) - obsoleted GetContentRegionMax(), GetWindowContentRegionMin() and GetWindowContentRegionMax(). (see #7838 on GitHub for more info)
442
                         you should never need those functions. you can do everything with GetCursorScreenPos() and GetContentRegionAvail() in a more simple way.
443
                            - instead of:  GetWindowContentRegionMax().x - GetCursorPos().x
444
                            - you can use: GetContentRegionAvail().x
445
                            - instead of:  GetWindowContentRegionMax().x + GetWindowPos().x
446
                            - you can use: GetCursorScreenPos().x + GetContentRegionAvail().x // when called from left edge of window
447
                            - instead of:  GetContentRegionMax()
448
                            - you can use: GetContentRegionAvail() + GetCursorScreenPos() - GetWindowPos() // right edge in local coordinates
449
                            - instead of:  GetWindowContentRegionMax().x - GetWindowContentRegionMin().x
450
                            - you can use: GetContentRegionAvail() // when called from left edge of window
451
 - 2024/07/15 (1.91.0) - renamed ImGuiSelectableFlags_DontClosePopups to ImGuiSelectableFlags_NoAutoClosePopups. (#1379, #1468, #2200, #4936, #5216, #7302, #7573)
452
                         (internals: also renamed ImGuiItemFlags_SelectableDontClosePopup into ImGuiItemFlags_AutoClosePopups with inverted behaviors)
453
 - 2024/07/15 (1.91.0) - obsoleted PushButtonRepeat()/PopButtonRepeat() in favor of using new PushItemFlag(ImGuiItemFlags_ButtonRepeat, ...)/PopItemFlag().
454
 - 2024/07/02 (1.91.0) - commented out obsolete ImGuiModFlags (renamed to ImGuiKeyChord in 1.89). (#4921, #456)
455
                       - commented out obsolete ImGuiModFlags_XXX values (renamed to ImGuiMod_XXX in 1.89). (#4921, #456)
456
                            - ImGuiModFlags_Ctrl -> ImGuiMod_Ctrl, ImGuiModFlags_Shift -> ImGuiMod_Shift etc.
457
 - 2024/07/02 (1.91.0) - IO, IME: renamed platform IME hook and added explicit context for consistency and future-proofness.
458
                            - old: io.SetPlatformImeDataFn(ImGuiViewport* viewport, ImGuiPlatformImeData* data);
459
                            - new: io.PlatformSetImeDataFn(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data);
460
 - 2024/06/21 (1.90.9) - BeginChild: added ImGuiChildFlags_NavFlattened as a replacement for the window flag ImGuiWindowFlags_NavFlattened: the feature only ever made sense for BeginChild() anyhow.
461
                            - old: BeginChild("Name", size, 0, ImGuiWindowFlags_NavFlattened);
462
                            - new: BeginChild("Name", size, ImGuiChildFlags_NavFlattened, 0);
463
 - 2024/06/21 (1.90.9) - io: ClearInputKeys() (first exposed in 1.89.8) doesn't clear mouse data, newly added ClearInputMouse() does.
464
 - 2024/06/20 (1.90.9) - renamed ImGuiDragDropFlags_SourceAutoExpirePayload to ImGuiDragDropFlags_PayloadAutoExpire.
465
 - 2024/06/18 (1.90.9) - style: renamed ImGuiCol_TabActive -> ImGuiCol_TabSelected, ImGuiCol_TabUnfocused -> ImGuiCol_TabDimmed, ImGuiCol_TabUnfocusedActive -> ImGuiCol_TabDimmedSelected.
466
 - 2024/06/10 (1.90.9) - removed old nested structure: renaming ImGuiStorage::ImGuiStoragePair type to ImGuiStoragePair (simpler for many languages).
467
 - 2024/06/06 (1.90.8) - reordered ImGuiInputTextFlags values. This should not be breaking unless you are using generated headers that have values not matching the main library.
468
 - 2024/06/06 (1.90.8) - removed 'ImGuiButtonFlags_MouseButtonDefault_ = ImGuiButtonFlags_MouseButtonLeft', was mostly unused and misleading.
469
 - 2024/05/27 (1.90.7) - commented out obsolete symbols marked obsolete in 1.88 (May 2022):
470
                            - old: CaptureKeyboardFromApp(bool)
471
                            - new: SetNextFrameWantCaptureKeyboard(bool)
472
                            - old: CaptureMouseFromApp(bool)
473
                            - new: SetNextFrameWantCaptureMouse(bool)
474
 - 2024/05/22 (1.90.7) - inputs (internals): renamed ImGuiKeyOwner_None to ImGuiKeyOwner_NoOwner, to make use more explicit and reduce confusion with the default it is a non-zero value and cannot be the default value (never made public, but disclosing as I expect a few users caught on owner-aware inputs).
475
                       - inputs (internals): renamed ImGuiInputFlags_RouteGlobalLow -> ImGuiInputFlags_RouteGlobal, ImGuiInputFlags_RouteGlobal -> ImGuiInputFlags_RouteGlobalOverFocused, ImGuiInputFlags_RouteGlobalHigh -> ImGuiInputFlags_RouteGlobalHighest.
476
                       - inputs (internals): Shortcut(), SetShortcutRouting(): swapped last two parameters order in function signatures:
477
                            - old: Shortcut(ImGuiKeyChord key_chord, ImGuiID owner_id = 0, ImGuiInputFlags flags = 0);
478
                            - new: Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags = 0, ImGuiID owner_id = 0);
479
                       - inputs (internals): owner-aware versions of IsKeyPressed(), IsKeyChordPressed(), IsMouseClicked(): swapped last two parameters order in function signatures.
480
                            - old: IsKeyPressed(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags = 0);
481
                            - new: IsKeyPressed(ImGuiKey key, ImGuiInputFlags flags, ImGuiID owner_id = 0);
482
                            - old: IsMouseClicked(ImGuiMouseButton button, ImGuiID owner_id, ImGuiInputFlags flags = 0);
483
                            - new: IsMouseClicked(ImGuiMouseButton button, ImGuiInputFlags flags, ImGuiID owner_id = 0);
484
                         for various reasons those changes makes sense. They are being made because making some of those API public.
485
                         only past users of imgui_internal.h with the extra parameters will be affected. Added asserts for valid flags in various functions to detect _some_ misuses, BUT NOT ALL.
486
 - 2024/05/21 (1.90.7) - docking: changed signature of DockSpaceOverViewport() to add explicit dockspace id if desired. pass 0 to use old behavior. (#7611)
487
                           - old: DockSpaceOverViewport(const ImGuiViewport* viewport = NULL, ImGuiDockNodeFlags flags = 0, ...);
488
                           - new: DockSpaceOverViewport(ImGuiID dockspace_id = 0, const ImGuiViewport* viewport = NULL, ImGuiDockNodeFlags flags = 0, ...);
489
 - 2024/05/16 (1.90.7) - inputs: on macOS X, Cmd and Ctrl keys are now automatically swapped by io.AddKeyEvent() as this naturally align with how macOS X uses those keys.
490
                           - it shouldn't really affect you unless you had custom shortcut swapping in place for macOS X apps.
491
                           - removed ImGuiMod_Shortcut which was previously dynamically remapping to Ctrl or Cmd/Super. It is now unnecessary to specific cross-platform idiomatic shortcuts. (#2343, #4084, #5923, #456)
492
 - 2024/05/14 (1.90.7) - backends: SDL_Renderer2 and SDL_Renderer3 backend now take a SDL_Renderer* in their RenderDrawData() functions.
493
 - 2024/04/18 (1.90.6) - TreeNode: Fixed a layout inconsistency when using an empty/hidden label followed by a SameLine() call. (#7505, #282)
494
                           - old: TreeNode("##Hidden"); SameLine(); Text("Hello");     // <-- This was actually incorrect! BUT appeared to look ok with the default style where ItemSpacing.x == FramePadding.x * 2 (it didn't look aligned otherwise).
495
                           - new: TreeNode("##Hidden"); SameLine(0, 0); Text("Hello"); // <-- This is correct for all styles values.
496
                         with the fix, IF you were successfully using TreeNode("")+SameLine(); you will now have extra spacing between your TreeNode and the following item.
497
                         You'll need to change the SameLine() call to SameLine(0,0) to remove this extraneous spacing. This seemed like the more sensible fix that's not making things less consistent.
498
                         (Note: when using this idiom you are likely to also use ImGuiTreeNodeFlags_SpanAvailWidth).
499
 - 2024/03/18 (1.90.5) - merged the radius_x/radius_y parameters in ImDrawList::AddEllipse(), AddEllipseFilled() and PathEllipticalArcTo() into a single ImVec2 parameter. Exceptionally, because those functions were added in 1.90, we are not adding inline redirection functions. The transition is easy and should affect few users. (#2743, #7417)
500
 - 2024/03/08 (1.90.5) - inputs: more formally obsoleted GetKeyIndex() when IMGUI_DISABLE_OBSOLETE_FUNCTIONS is set. It has been unnecessary and a no-op since 1.87 (it returns the same value as passed when used with a 1.87+ backend using io.AddKeyEvent() function). (#4921)
501
                           - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX)) -> use IsKeyPressed(ImGuiKey_XXX)
502
 - 2024/01/15 (1.90.2) - commented out obsolete ImGuiIO::ImeWindowHandle marked obsolete in 1.87, favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'.
503
 - 2023/12/19 (1.90.1) - commented out obsolete ImGuiKey_KeyPadEnter redirection to ImGuiKey_KeypadEnter.
504
 - 2023/11/06 (1.90.1) - removed CalcListClipping() marked obsolete in 1.86. Prefer using ImGuiListClipper which can return non-contiguous ranges.
505
 - 2023/11/05 (1.90.1) - imgui_freetype: commented out ImGuiFreeType::BuildFontAtlas() obsoleted in 1.81. prefer using #define IMGUI_ENABLE_FREETYPE or see commented code for manual calls.
506
 - 2023/11/05 (1.90.1) - internals,columns: commented out legacy ImGuiColumnsFlags_XXX symbols redirecting to ImGuiOldColumnsFlags_XXX, obsoleted from imgui_internal.h in 1.80.
507
 - 2023/11/09 (1.90.0) - removed IM_OFFSETOF() macro in favor of using offsetof() available in C++11. Kept redirection define (will obsolete).
508
 - 2023/11/07 (1.90.0) - removed BeginChildFrame()/EndChildFrame() in favor of using BeginChild() with the ImGuiChildFlags_FrameStyle flag. kept inline redirection function (will obsolete).
509
                         those functions were merely PushStyle/PopStyle helpers, the removal isn't so much motivated by needing to add the feature in BeginChild(), but by the necessity to avoid BeginChildFrame() signature mismatching BeginChild() signature and features.
510
 - 2023/11/02 (1.90.0) - BeginChild: upgraded 'bool border = true' parameter to 'ImGuiChildFlags flags' type, added ImGuiChildFlags_Border equivalent. As with our prior "bool-to-flags" API updates, the ImGuiChildFlags_Border value is guaranteed to be == true forever to ensure a smoother transition, meaning all existing calls will still work.
511
                           - old: BeginChild("Name", size, true)
512
                           - new: BeginChild("Name", size, ImGuiChildFlags_Border)
513
                           - old: BeginChild("Name", size, false)
514
                           - new: BeginChild("Name", size) or BeginChild("Name", 0) or BeginChild("Name", size, ImGuiChildFlags_None)
515
 - 2023/11/02 (1.90.0) - BeginChild: added child-flag ImGuiChildFlags_AlwaysUseWindowPadding as a replacement for the window-flag ImGuiWindowFlags_AlwaysUseWindowPadding: the feature only ever made sense for BeginChild() anyhow.
516
                           - old: BeginChild("Name", size, 0, ImGuiWindowFlags_AlwaysUseWindowPadding);
517
                           - new: BeginChild("Name", size, ImGuiChildFlags_AlwaysUseWindowPadding, 0);
518
 - 2023/09/27 (1.90.0) - io: removed io.MetricsActiveAllocations introduced in 1.63. Same as 'g.DebugMemAllocCount - g.DebugMemFreeCount' (still displayed in Metrics, unlikely to be accessed by end-user).
519
 - 2023/09/26 (1.90.0) - debug tools: Renamed ShowStackToolWindow() ("Stack Tool") to ShowIDStackToolWindow() ("ID Stack Tool"), as earlier name was misleading. Kept inline redirection function. (#4631)
520
 - 2023/09/15 (1.90.0) - ListBox, Combo: changed signature of "name getter" callback in old one-liner ListBox()/Combo() apis. kept inline redirection function (will obsolete).
521
                           - old: bool Combo(const char* label, int* current_item, bool (*getter)(void* user_data, int idx, const char** out_text), ...)
522
                           - new: bool Combo(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...);
523
                           - old: bool ListBox(const char* label, int* current_item, bool (*getting)(void* user_data, int idx, const char** out_text), ...);
524
                           - new: bool ListBox(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...);
525
 - 2023/09/08 (1.90.0) - commented out obsolete redirecting functions:
526
                           - GetWindowContentRegionWidth()  -> use GetWindowContentRegionMax().x - GetWindowContentRegionMin().x. Consider that generally 'GetContentRegionAvail().x' is more useful.
527
                           - ImDrawCornerFlags_XXX          -> use ImDrawFlags_RoundCornersXXX flags. Read 1.82 Changelog for details + grep commented names in sources.
528
                       - commented out runtime support for hardcoded ~0 or 0x01..0x0F rounding flags values for AddRect()/AddRectFilled()/PathRect()/AddImageRounded() -> use ImDrawFlags_RoundCornersXXX flags. Read 1.82 Changelog for details
529
 - 2023/08/25 (1.89.9) - clipper: Renamed IncludeRangeByIndices() (also called ForceDisplayRangeByIndices() before 1.89.6) to IncludeItemsByIndex(). Kept inline redirection function. Sorry!
530
 - 2023/07/12 (1.89.8) - ImDrawData: CmdLists now owned, changed from ImDrawList** to ImVector<ImDrawList*>. Majority of users shouldn't be affected, but you cannot compare to NULL nor reassign manually anymore. Instead use AddDrawList(). (#6406, #4879, #1878)
531
 - 2023/06/28 (1.89.7) - overlapping items: obsoleted 'SetItemAllowOverlap()' (called after item) in favor of calling 'SetNextItemAllowOverlap()' (called before item). 'SetItemAllowOverlap()' didn't and couldn't work reliably since 1.89 (2022-11-15).
532
 - 2023/06/28 (1.89.7) - overlapping items: renamed 'ImGuiTreeNodeFlags_AllowItemOverlap' to 'ImGuiTreeNodeFlags_AllowOverlap', 'ImGuiSelectableFlags_AllowItemOverlap' to 'ImGuiSelectableFlags_AllowOverlap'. Kept redirecting enums (will obsolete).
533
 - 2023/06/28 (1.89.7) - overlapping items: IsItemHovered() now by default return false when querying an item using AllowOverlap mode which is being overlapped. Use ImGuiHoveredFlags_AllowWhenOverlappedByItem to revert to old behavior.
534
 - 2023/06/28 (1.89.7) - overlapping items: Selectable and TreeNode don't allow overlap when active so overlapping widgets won't appear as hovered. While this fixes a common small visual issue, it also means that calling IsItemHovered() after a non-reactive elements - e.g. Text() - overlapping an active one may fail if you don't use IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem). (#6610)
535
 - 2023/06/20 (1.89.7) - moved io.HoverDelayShort/io.HoverDelayNormal to style.HoverDelayShort/style.HoverDelayNormal. As the fields were added in 1.89 and expected to be left unchanged by most users, or only tweaked once during app initialization, we are exceptionally accepting the breakage.
536
 - 2023/05/30 (1.89.6) - backends: renamed "imgui_impl_sdlrenderer.cpp" to "imgui_impl_sdlrenderer2.cpp" and "imgui_impl_sdlrenderer.h" to "imgui_impl_sdlrenderer2.h". This is in prevision for the future release of SDL3.
537
 - 2023/05/22 (1.89.6) - listbox: commented out obsolete/redirecting functions that were marked obsolete more than two years ago:
538
                           - ListBoxHeader()  -> use BeginListBox() (note how two variants of ListBoxHeader() existed. Check commented versions in imgui.h for reference)
539
                           - ListBoxFooter()  -> use EndListBox()
540
 - 2023/05/15 (1.89.6) - clipper: commented out obsolete redirection constructor 'ImGuiListClipper(int items_count, float items_height = -1.0f)' that was marked obsolete in 1.79. Use default constructor + clipper.Begin().
541
 - 2023/05/15 (1.89.6) - clipper: renamed ImGuiListClipper::ForceDisplayRangeByIndices() to ImGuiListClipper::IncludeRangeByIndices().
542
 - 2023/03/14 (1.89.4) - commented out redirecting enums/functions names that were marked obsolete two years ago:
543
                           - ImGuiSliderFlags_ClampOnInput        -> use ImGuiSliderFlags_AlwaysClamp
544
                           - ImGuiInputTextFlags_AlwaysInsertMode -> use ImGuiInputTextFlags_AlwaysOverwrite
545
                           - ImDrawList::AddBezierCurve()         -> use ImDrawList::AddBezierCubic()
546
                           - ImDrawList::PathBezierCurveTo()      -> use ImDrawList::PathBezierCubicCurveTo()
547
 - 2023/03/09 (1.89.4) - renamed PushAllowKeyboardFocus()/PopAllowKeyboardFocus() to PushTabStop()/PopTabStop(). Kept inline redirection functions (will obsolete).
548
 - 2023/03/09 (1.89.4) - tooltips: Added 'bool' return value to BeginTooltip() for API consistency. Please only submit contents and call EndTooltip() if BeginTooltip() returns true. In reality the function will _currently_ always return true, but further changes down the line may change this, best to clarify API sooner.
549
 - 2023/02/15 (1.89.4) - moved the optional "courtesy maths operators" implementation from imgui_internal.h in imgui.h.
550
                         Even though we encourage using your own maths types and operators by setting up IM_VEC2_CLASS_EXTRA,
551
                         it has been frequently requested by people to use our own. We had an opt-in define which was
552
                         previously fulfilled in imgui_internal.h. It is now fulfilled in imgui.h. (#6164)
553
                           - OK:     #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui.h" / #include "imgui_internal.h"
554
                           - Error:  #include "imgui.h" / #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui_internal.h"
555
 - 2023/02/07 (1.89.3) - backends: renamed "imgui_impl_sdl.cpp" to "imgui_impl_sdl2.cpp" and "imgui_impl_sdl.h" to "imgui_impl_sdl2.h". (#6146) This is in prevision for the future release of SDL3.
556
 - 2022/10/26 (1.89)   - commented out redirecting OpenPopupContextItem() which was briefly the name of OpenPopupOnItemClick() from 1.77 to 1.79.
557
 - 2022/10/12 (1.89)   - removed runtime patching of invalid "%f"/"%0.f" format strings for DragInt()/SliderInt(). This was obsoleted in 1.61 (May 2018). See 1.61 changelog for details.
558
 - 2022/09/26 (1.89)   - renamed and merged keyboard modifiers key enums and flags into a same set. Kept inline redirection enums (will obsolete).
559
                           - ImGuiKey_ModCtrl  and ImGuiModFlags_Ctrl  -> ImGuiMod_Ctrl
560
                           - ImGuiKey_ModShift and ImGuiModFlags_Shift -> ImGuiMod_Shift
561
                           - ImGuiKey_ModAlt   and ImGuiModFlags_Alt   -> ImGuiMod_Alt
562
                           - ImGuiKey_ModSuper and ImGuiModFlags_Super -> ImGuiMod_Super
563
                         the ImGuiKey_ModXXX were introduced in 1.87 and mostly used by backends.
564
                         the ImGuiModFlags_XXX have been exposed in imgui.h but not really used by any public api only by third-party extensions.
565
                         exceptionally commenting out the older ImGuiKeyModFlags_XXX names ahead of obsolescence schedule to reduce confusion and because they were not meant to be used anyway.
566
 - 2022/09/20 (1.89)   - ImGuiKey is now a typed enum, allowing ImGuiKey_XXX symbols to be named in debuggers.
567
                         this will require uses of legacy backend-dependent indices to be casted, e.g.
568
                            - with imgui_impl_glfw:  IsKeyPressed(GLFW_KEY_A) -> IsKeyPressed((ImGuiKey)GLFW_KEY_A);
569
                            - with imgui_impl_win32: IsKeyPressed('A')        -> IsKeyPressed((ImGuiKey)'A')
570
                            - etc. However if you are upgrading code you might well use the better, backend-agnostic IsKeyPressed(ImGuiKey_A) now!
571
 - 2022/09/12 (1.89) - removed the bizarre legacy default argument for 'TreePush(const void* ptr = NULL)', always pass a pointer value explicitly. NULL/nullptr is ok but require cast, e.g. TreePush((void*)nullptr);
572
 - 2022/09/05 (1.89) - commented out redirecting functions/enums names that were marked obsolete in 1.77 and 1.78 (June 2020):
573
                         - DragScalar(), DragScalarN(), DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
574
                         - SliderScalar(), SliderScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
575
                         - BeginPopupContextWindow(const char*, ImGuiMouseButton, bool) -> use BeginPopupContextWindow(const char*, ImGuiPopupFlags)
576
 - 2022/09/02 (1.89) - obsoleted using SetCursorPos()/SetCursorScreenPos() to extend parent window/cell boundaries.
577
                       this relates to when moving the cursor position beyond current boundaries WITHOUT submitting an item.
578
                         - previously this would make the window content size ~200x200:
579
                              Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();
580
                         - instead, please submit an item:
581
                              Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End();
582
                         - alternative:
583
                              Begin(...) + Dummy(ImVec2(200,200)) + End();
584
                         - content size is now only extended when submitting an item!
585
                         - with '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will now be detected and assert.
586
                         - without '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will silently be fixed until we obsolete it.
587
 - 2022/08/03 (1.89) - changed signature of ImageButton() function. Kept redirection function (will obsolete).
588
                        - added 'const char* str_id' parameter + removed 'int frame_padding = -1' parameter.
589
                        - old signature: bool ImageButton(ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), int frame_padding = -1, ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
590
                          - used the ImTextureID value to create an ID. This was inconsistent with other functions, led to ID conflicts, and caused problems with engines using transient ImTextureID values.
591
                          - had a FramePadding override which was inconsistent with other functions and made the already-long signature even longer.
592
                        - new signature: bool ImageButton(const char* str_id, ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
593
                          - requires an explicit identifier. You may still use e.g. PushID() calls and then pass an empty identifier.
594
                          - always uses style.FramePadding for padding, to be consistent with other buttons. You may use PushStyleVar() to alter this.
595
 - 2022/07/08 (1.89) - inputs: removed io.NavInputs[] and ImGuiNavInput enum (following 1.87 changes).
596
                        - Official backends from 1.87+                  -> no issue.
597
                        - Official backends from 1.60 to 1.86           -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need updating!
598
                        - Custom backends not writing to io.NavInputs[] -> no issue.
599
                        - Custom backends writing to io.NavInputs[]     -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need fixing!
600
                        - TL;DR: Backends should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values instead of filling io.NavInput[].
601
 - 2022/06/15 (1.88) - renamed IMGUI_DISABLE_METRICS_WINDOW to IMGUI_DISABLE_DEBUG_TOOLS for correctness. kept support for old define (will obsolete).
602
 - 2022/05/03 (1.88) - backends: osx: removed ImGui_ImplOSX_HandleEvent() from backend API in favor of backend automatically handling event capture. All ImGui_ImplOSX_HandleEvent() calls should be removed as they are now unnecessary.
603
 - 2022/04/05 (1.88) - inputs: renamed ImGuiKeyModFlags to ImGuiModFlags. Kept inline redirection enums (will obsolete). This was never used in public API functions but technically present in imgui.h and ImGuiIO.
604
 - 2022/01/20 (1.87) - inputs: reworded gamepad IO.
605
                        - Backend writing to io.NavInputs[]            -> backend should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values.
606
 - 2022/01/19 (1.87) - sliders, drags: removed support for legacy arithmetic operators (+,+-,*,/) when inputing text. This doesn't break any api/code but a feature that used to be accessible by end-users (which seemingly no one used).
607
 - 2022/01/17 (1.87) - inputs: reworked mouse IO.
608
                        - Backend writing to io.MousePos               -> backend should call io.AddMousePosEvent()
609
                        - Backend writing to io.MouseDown[]            -> backend should call io.AddMouseButtonEvent()
610
                        - Backend writing to io.MouseWheel             -> backend should call io.AddMouseWheelEvent()
611
                        - Backend writing to io.MouseHoveredViewport   -> backend should call io.AddMouseViewportEvent() [Docking branch w/ multi-viewports only]
612
                       note: for all calls to IO new functions, the Dear ImGui context should be bound/current.
613
                       read https://github.com/ocornut/imgui/issues/4921 for details.
614
 - 2022/01/10 (1.87) - inputs: reworked keyboard IO. Removed io.KeyMap[], io.KeysDown[] in favor of calling io.AddKeyEvent(). Removed GetKeyIndex(), now unnecessary. All IsKeyXXX() functions now take ImGuiKey values. All features are still functional until IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Read Changelog and Release Notes for details.
615
                        - IsKeyPressed(MY_NATIVE_KEY_XXX)              -> use IsKeyPressed(ImGuiKey_XXX)
616
                        - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX))      -> use IsKeyPressed(ImGuiKey_XXX)
617
                        - Backend writing to io.KeyMap[],io.KeysDown[] -> backend should call io.AddKeyEvent() (+ call io.SetKeyEventNativeData() if you want legacy user code to stil function with legacy key codes).
618
                        - Backend writing to io.KeyCtrl, io.KeyShift.. -> backend should call io.AddKeyEvent() with ImGuiMod_XXX values. *IF YOU PULLED CODE BETWEEN 2021/01/10 and 2021/01/27: We used to have a io.AddKeyModsEvent() function which was now replaced by io.AddKeyEvent() with ImGuiMod_XXX values.*
619
                     - one case won't work with backward compatibility: if your custom backend used ImGuiKey as mock native indices (e.g. "io.KeyMap[ImGuiKey_A] = ImGuiKey_A") because those values are now larger than the legacy KeyDown[] array. Will assert.
620
                     - inputs: added ImGuiKey_ModCtrl/ImGuiKey_ModShift/ImGuiKey_ModAlt/ImGuiKey_ModSuper values to submit keyboard modifiers using io.AddKeyEvent(), instead of writing directly to io.KeyCtrl, io.KeyShift, io.KeyAlt, io.KeySuper.
621
 - 2022/01/05 (1.87) - inputs: renamed ImGuiKey_KeyPadEnter to ImGuiKey_KeypadEnter to align with new symbols. Kept redirection enum.
622
 - 2022/01/05 (1.87) - removed io.ImeSetInputScreenPosFn() in favor of more flexible io.SetPlatformImeDataFn(). Removed 'void* io.ImeWindowHandle' in favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'.
623
 - 2022/01/01 (1.87) - commented out redirecting functions/enums names that were marked obsolete in 1.69, 1.70, 1.71, 1.72 (March-July 2019)
624
                        - ImGui::SetNextTreeNodeOpen()        -> use ImGui::SetNextItemOpen()
625
                        - ImGui::GetContentRegionAvailWidth() -> use ImGui::GetContentRegionAvail().x
626
                        - ImGui::TreeAdvanceToLabelPos()      -> use ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetTreeNodeToLabelSpacing());
627
                        - ImFontAtlas::CustomRect             -> use ImFontAtlasCustomRect
628
                        - ImGuiColorEditFlags_RGB/HSV/HEX     -> use ImGuiColorEditFlags_DisplayRGB/HSV/Hex
629
 - 2021/12/20 (1.86) - backends: removed obsolete Marmalade backend (imgui_impl_marmalade.cpp) + example. Find last supported version at https://github.com/ocornut/imgui/wiki/Bindings
630
 - 2021/11/04 (1.86) - removed CalcListClipping() function. Prefer using ImGuiListClipper which can return non-contiguous ranges. Please open an issue if you think you really need this function.
631
 - 2021/08/23 (1.85) - removed GetWindowContentRegionWidth() function. keep inline redirection helper. can use 'GetWindowContentRegionMax().x - GetWindowContentRegionMin().x' instead for generally 'GetContentRegionAvail().x' is more useful.
632
 - 2021/07/26 (1.84) - commented out redirecting functions/enums names that were marked obsolete in 1.67 and 1.69 (March 2019):
633
                        - ImGui::GetOverlayDrawList() -> use ImGui::GetForegroundDrawList()
634
                        - ImFont::GlyphRangesBuilder  -> use ImFontGlyphRangesBuilder
635
 - 2021/05/19 (1.83) - backends: obsoleted direct access to ImDrawCmd::TextureId in favor of calling ImDrawCmd::GetTexID().
636
                        - if you are using official backends from the source tree: you have nothing to do.
637
                        - if you have copied old backend code or using your own: change access to draw_cmd->TextureId to draw_cmd->GetTexID().
638
 - 2021/03/12 (1.82) - upgraded ImDrawList::AddRect(), AddRectFilled(), PathRect() to use ImDrawFlags instead of ImDrawCornersFlags.
639
                        - ImDrawCornerFlags_TopLeft  -> use ImDrawFlags_RoundCornersTopLeft
640
                        - ImDrawCornerFlags_BotRight -> use ImDrawFlags_RoundCornersBottomRight
641
                        - ImDrawCornerFlags_None     -> use ImDrawFlags_RoundCornersNone etc.
642
                       flags now sanely defaults to 0 instead of 0x0F, consistent with all other flags in the API.
643
                       breaking: the default with rounding > 0.0f is now "round all corners" vs old implicit "round no corners":
644
                        - rounding == 0.0f + flags == 0 --> meant no rounding  --> unchanged (common use)
645
                        - rounding  > 0.0f + flags != 0 --> meant rounding     --> unchanged (common use)
646
                        - rounding == 0.0f + flags != 0 --> meant no rounding  --> unchanged (unlikely use)
647
                        - rounding  > 0.0f + flags == 0 --> meant no rounding  --> BREAKING (unlikely use): will now round all corners --> use ImDrawFlags_RoundCornersNone or rounding == 0.0f.
648
                       this ONLY matters for hard coded use of 0 + rounding > 0.0f. Use of named ImDrawFlags_RoundCornersNone (new) or ImDrawCornerFlags_None (old) are ok.
649
                       the old ImDrawCornersFlags used awkward default values of ~0 or 0xF (4 lower bits set) to signify "round all corners" and we sometimes encouraged using them as shortcuts.
650
                       legacy path still support use of hard coded ~0 or any value from 0x1 or 0xF. They will behave the same with legacy paths enabled (will assert otherwise).
651
 - 2021/03/11 (1.82) - removed redirecting functions/enums names that were marked obsolete in 1.66 (September 2018):
652
                        - ImGui::SetScrollHere()              -> use ImGui::SetScrollHereY()
653
 - 2021/03/11 (1.82) - clarified that ImDrawList::PathArcTo(), ImDrawList::PathArcToFast() won't render with radius < 0.0f. Previously it sorts of accidentally worked but would generally lead to counter-clockwise paths and have an effect on anti-aliasing.
654
 - 2021/03/10 (1.82) - upgraded ImDrawList::AddPolyline() and PathStroke() "bool closed" parameter to "ImDrawFlags flags". The matching ImDrawFlags_Closed value is guaranteed to always stay == 1 in the future.
655
 - 2021/02/22 (1.82) - (*undone in 1.84*) win32+mingw: Re-enabled IME functions by default even under MinGW. In July 2016, issue #738 had me incorrectly disable those default functions for MinGW. MinGW users should: either link with -limm32, either set their imconfig file  with '#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS'.
656
 - 2021/02/17 (1.82) - renamed rarely used style.CircleSegmentMaxError (old default = 1.60f) to style.CircleTessellationMaxError (new default = 0.30f) as the meaning of the value changed.
657
 - 2021/02/03 (1.81) - renamed ListBoxHeader(const char* label, ImVec2 size) to BeginListBox(). Kept inline redirection function (will obsolete).
658
                     - removed ListBoxHeader(const char* label, int items_count, int height_in_items = -1) in favor of specifying size. Kept inline redirection function (will obsolete).
659
                     - renamed ListBoxFooter() to EndListBox(). Kept inline redirection function (will obsolete).
660
 - 2021/01/26 (1.81) - removed ImGuiFreeType::BuildFontAtlas(). Kept inline redirection function. Prefer using '#define IMGUI_ENABLE_FREETYPE', but there's a runtime selection path available too. The shared extra flags parameters (very rarely used) are now stored in ImFontAtlas::FontBuilderFlags.
661
                     - renamed ImFontConfig::RasterizerFlags (used by FreeType) to ImFontConfig::FontBuilderFlags.
662
                     - renamed ImGuiFreeType::XXX flags to ImGuiFreeTypeBuilderFlags_XXX for consistency with other API.
663
 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.63 (August 2018):
664
                        - ImGui::IsItemDeactivatedAfterChange() -> use ImGui::IsItemDeactivatedAfterEdit().
665
                        - ImGuiCol_ModalWindowDarkening       -> use ImGuiCol_ModalWindowDimBg
666
                        - ImGuiInputTextCallback              -> use ImGuiTextEditCallback
667
                        - ImGuiInputTextCallbackData          -> use ImGuiTextEditCallbackData
668
 - 2020/12/21 (1.80) - renamed ImDrawList::AddBezierCurve() to AddBezierCubic(), and PathBezierCurveTo() to PathBezierCubicCurveTo(). Kept inline redirection function (will obsolete).
669
 - 2020/12/04 (1.80) - added imgui_tables.cpp file! Manually constructed project files will need the new file added!
670
 - 2020/11/18 (1.80) - renamed undocumented/internals ImGuiColumnsFlags_* to ImGuiOldColumnFlags_* in prevision of incoming Tables API.
671
 - 2020/11/03 (1.80) - renamed io.ConfigWindowsMemoryCompactTimer to io.ConfigMemoryCompactTimer as the feature will apply to other data structures
672
 - 2020/10/14 (1.80) - backends: moved all backends files (imgui_impl_XXXX.cpp, imgui_impl_XXXX.h) from examples/ to backends/.
673
 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.60 (April 2018):
674
                        - io.RenderDrawListsFn pointer        -> use ImGui::GetDrawData() value and call the render function of your backend
675
                        - ImGui::IsAnyWindowFocused()         -> use ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow)
676
                        - ImGui::IsAnyWindowHovered()         -> use ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
677
                        - ImGuiStyleVar_Count_                -> use ImGuiStyleVar_COUNT
678
                        - ImGuiMouseCursor_Count_             -> use ImGuiMouseCursor_COUNT
679
                      - removed redirecting functions names that were marked obsolete in 1.61 (May 2018):
680
                        - InputFloat (... int decimal_precision ...) -> use InputFloat (... const char* format ...) with format = "%.Xf" where X is your value for decimal_precision.
681
                        - same for InputFloat2()/InputFloat3()/InputFloat4() variants taking a `int decimal_precision` parameter.
682
 - 2020/10/05 (1.79) - removed ImGuiListClipper: Renamed constructor parameters which created an ambiguous alternative to using the ImGuiListClipper::Begin() function, with misleading edge cases (note: imgui_memory_editor <0.40 from imgui_club/ used this old clipper API. Update your copy if needed).
683
 - 2020/09/25 (1.79) - renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. Kept redirection enum (will obsolete sooner because previous name was added recently).
684
 - 2020/09/25 (1.79) - renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton.
685
 - 2020/09/21 (1.79) - renamed OpenPopupContextItem() back to OpenPopupOnItemClick(), reverting the change from 1.77. For varieties of reason this is more self-explanatory.
686
 - 2020/09/21 (1.79) - removed return value from OpenPopupOnItemClick() - returned true on mouse release on an item - because it is inconsistent with other popup APIs and makes others misleading. It's also and unnecessary: you can use IsWindowAppearing() after BeginPopup() for a similar result.
687
 - 2020/09/17 (1.79) - removed ImFont::DisplayOffset in favor of ImFontConfig::GlyphOffset. DisplayOffset was applied after scaling and not very meaningful/useful outside of being needed by the default ProggyClean font. If you scaled this value after calling AddFontDefault(), this is now done automatically. It was also getting in the way of better font scaling, so let's get rid of it now!
688
 - 2020/08/17 (1.78) - obsoleted use of the trailing 'float power=1.0f' parameter for DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(), DragFloatRange2(), DragScalar(), DragScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(), SliderScalar(), SliderScalarN(), VSliderFloat() and VSliderScalar().
689
                       replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags).
690
                       worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. in short, when calling those functions:
691
                       - if you omitted the 'power' parameter (likely!), you are not affected.
692
                       - if you set the 'power' parameter to 1.0f (same as previous default value): 1/ your compiler may warn on float>int conversion, 2/ everything else will work. 3/ you can replace the 1.0f value with 0 to fix the warning, and be technically correct.
693
                       - if you set the 'power' parameter to >1.0f (to enable non-linear editing): 1/ your compiler may warn on float>int conversion, 2/ code will assert at runtime, 3/ in case asserts are disabled, the code will not crash and enable the _Logarithmic flag. 4/ you can replace the >1.0f value with ImGuiSliderFlags_Logarithmic to fix the warning/assert and get a _similar_ effect as previous uses of power >1.0f.
694
                       see https://github.com/ocornut/imgui/issues/3361 for all details.
695
                       kept inline redirection functions (will obsolete) apart for: DragFloatRange2(), VSliderFloat(), VSliderScalar(). For those three the 'float power=1.0f' version was removed directly as they were most unlikely ever used.
696
                       for shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`.
697
                     - obsoleted use of v_min > v_max in DragInt, DragFloat, DragScalar to lock edits (introduced in 1.73, was not demoed nor documented very), will be replaced by a more generic ReadOnly feature. You may use the ImGuiSliderFlags_ReadOnly internal flag in the meantime.
698
 - 2020/06/23 (1.77) - removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems.
699
 - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). [NOTE: THIS WAS REVERTED IN 1.79]
700
 - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017.
701
 - 2020/04/23 (1.77) - removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular().
702
 - 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more.
703
 - 2019/12/17 (1.75) - [undid this change in 1.76] made Columns() limited to 64 columns by asserting above that limit. While the current code technically supports it, future code may not so we're putting the restriction ahead.
704
 - 2019/12/13 (1.75) - [imgui_internal.h] changed ImRect() default constructor initializes all fields to 0.0f instead of (FLT_MAX,FLT_MAX,-FLT_MAX,-FLT_MAX). If you used ImRect::Add() to create bounding boxes by adding multiple points into it, you may need to fix your initial value.
705
 - 2019/12/08 (1.75) - removed redirecting functions/enums that were marked obsolete in 1.53 (December 2017):
706
                       - ShowTestWindow()                    -> use ShowDemoWindow()
707
                       - IsRootWindowFocused()               -> use IsWindowFocused(ImGuiFocusedFlags_RootWindow)
708
                       - IsRootWindowOrAnyChildFocused()     -> use IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)
709
                       - SetNextWindowContentWidth(w)        -> use SetNextWindowContentSize(ImVec2(w, 0.0f)
710
                       - GetItemsLineHeightWithSpacing()     -> use GetFrameHeightWithSpacing()
711
                       - ImGuiCol_ChildWindowBg              -> use ImGuiCol_ChildBg
712
                       - ImGuiStyleVar_ChildWindowRounding   -> use ImGuiStyleVar_ChildRounding
713
                       - ImGuiTreeNodeFlags_AllowOverlapMode -> use ImGuiTreeNodeFlags_AllowItemOverlap
714
                       - IMGUI_DISABLE_TEST_WINDOWS          -> use IMGUI_DISABLE_DEMO_WINDOWS
715
 - 2019/12/08 (1.75) - obsoleted calling ImDrawList::PrimReserve() with a negative count (which was vaguely documented and rarely if ever used). Instead, we added an explicit PrimUnreserve() API.
716
 - 2019/12/06 (1.75) - removed implicit default parameter to IsMouseDragging(int button = 0) to be consistent with other mouse functions (none of the other functions have it).
717
 - 2019/11/21 (1.74) - ImFontAtlas::AddCustomRectRegular() now requires an ID larger than 0x110000 (instead of 0x10000) to conform with supporting Unicode planes 1-16 in a future update. ID below 0x110000 will now assert.
718
 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS to IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS for consistency.
719
 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_MATH_FUNCTIONS to IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS for consistency.
720
 - 2019/10/22 (1.74) - removed redirecting functions/enums that were marked obsolete in 1.52 (October 2017):
721
                       - Begin() [old 5 args version]        -> use Begin() [3 args], use SetNextWindowSize() SetNextWindowBgAlpha() if needed
722
                       - IsRootWindowOrAnyChildHovered()     -> use IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows)
723
                       - AlignFirstTextHeightToWidgets()     -> use AlignTextToFramePadding()
724
                       - SetNextWindowPosCenter()            -> use SetNextWindowPos() with a pivot of (0.5f, 0.5f)
725
                       - ImFont::Glyph                       -> use ImFontGlyph
726
 - 2019/10/14 (1.74) - inputs: Fixed a miscalculation in the keyboard/mouse "typematic" repeat delay/rate calculation, used by keys and e.g. repeating mouse buttons as well as the GetKeyPressedAmount() function.
727
                       if you were using a non-default value for io.KeyRepeatRate (previous default was 0.250), you can add +io.KeyRepeatDelay to it to compensate for the fix.
728
                       The function was triggering on: 0.0 and (delay+rate*N) where (N>=1). Fixed formula responds to (N>=0). Effectively it made io.KeyRepeatRate behave like it was set to (io.KeyRepeatRate + io.KeyRepeatDelay).
729
                       If you never altered io.KeyRepeatRate nor used GetKeyPressedAmount() this won't affect you.
730
 - 2019/07/15 (1.72) - removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). Kept redirection function (will obsolete).
731
 - 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete).
732
 - 2019/06/14 (1.72) - removed redirecting functions/enums names that were marked obsolete in 1.51 (June 2017): ImGuiCol_Column*, ImGuiSetCond_*, IsItemHoveredRect(), IsPosHoveringAnyWindow(), IsMouseHoveringAnyWindow(), IsMouseHoveringWindow(), IMGUI_ONCE_UPON_A_FRAME. Grep this log for details and new names, or see how they were implemented until 1.71.
733
 - 2019/06/07 (1.71) - rendering of child window outer decorations (bg color, border, scrollbars) is now performed as part of the parent window. If you have
734
                       overlapping child windows in a same parent, and relied on their relative z-order to be mapped to their submission order, this will affect your rendering.
735
                       This optimization is disabled if the parent window has no visual output, because it appears to be the most common situation leading to the creation of overlapping child windows.
736
                       Please reach out if you are affected.
737
 - 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete).
738
 - 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c).
739
 - 2019/04/29 (1.70) - improved ImDrawList thick strokes (>1.0f) preserving correct thickness up to 90 degrees angles (e.g. rectangles). If you have custom rendering using thick lines, they will appear thicker now.
740
 - 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete).
741
 - 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete).
742
 - 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete).
743
 - 2019/02/14 (1.68) - made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). If for some reason your time step calculation gives you a zero value, replace it with an arbitrarily small value!
744
 - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already).
745
 - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead!
746
 - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete).
747
 - 2018/12/20 (1.67) - made it illegal to call Begin("") with an empty string. This somehow half-worked before but had various undesirable side-effects.
748
 - 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags.
749
 - 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files.
750
 - 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete).
751
 - 2018/09/06 (1.65) - renamed stb_truetype.h to imstb_truetype.h, stb_textedit.h to imstb_textedit.h, and stb_rect_pack.h to imstb_rectpack.h.
752
                       If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths.
753
 - 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427)
754
 - 2018/08/31 (1.64) - added imgui_widgets.cpp file, extracted and moved widgets code out of imgui.cpp into imgui_widgets.cpp. Re-ordered some of the code remaining in imgui.cpp.
755
                       NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED.
756
                       Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions.
757
 - 2018/08/22 (1.63) - renamed IsItemDeactivatedAfterChange() to IsItemDeactivatedAfterEdit() for consistency with new IsItemEdited() API. Kept redirection function (will obsolete soonish as IsItemDeactivatedAfterChange() is very recent).
758
 - 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete).
759
 - 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly).
760
 - 2018/08/01 (1.63) - removed per-window ImGuiWindowFlags_ResizeFromAnySide beta flag in favor of a global io.ConfigResizeWindowsFromEdges [update 1.67 renamed to ConfigWindowsResizeFromEdges] to enable the feature.
761
 - 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency.
762
 - 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time.
763
 - 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete).
764
 - 2018/06/08 (1.62) - examples: the imgui_impl_XXX files have been split to separate platform (Win32, GLFW, SDL2, etc.) from renderer (DX11, OpenGL, Vulkan,  etc.).
765
                       old backends will still work as is, however prefer using the separated backends as they will be updated to support multi-viewports.
766
                       when adopting new backends follow the main.cpp code of your preferred examples/ folder to know which functions to call.
767
                       in particular, note that old backends called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function.
768
 - 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set.
769
 - 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.
770
 - 2018/05/03 (1.61) - DragInt(): the default compile-time format string has been changed from "%.0f" to "%d", as we are not using integers internally any more.
771
                       If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format.
772
                       To honor backward-compatibility, the DragInt() code will currently parse and modify format strings to replace %*f with %d, giving time to users to upgrade their code.
773
                       If you have IMGUI_DISABLE_OBSOLETE_FUNCTIONS enabled, the code will instead assert! You may run a reg-exp search on your codebase for e.g. "DragInt.*%f" to help you find them.
774
 - 2018/04/28 (1.61) - obsoleted InputFloat() functions taking an optional "int decimal_precision" in favor of an equivalent and more flexible "const char* format",
775
                       consistent with other functions. Kept redirection functions (will obsolete).
776
 - 2018/04/09 (1.61) - IM_DELETE() helper function added in 1.60 doesn't clear the input _pointer_ reference, more consistent with expectation and allows passing r-value.
777
 - 2018/03/20 (1.60) - renamed io.WantMoveMouse to io.WantSetMousePos for consistency and ease of understanding (was added in 1.52, _not_ used by core and only honored by some backend ahead of merging the Nav branch).
778
 - 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now.
779
 - 2018/03/08 (1.60) - changed ImFont::DisplayOffset.y to default to 0 instead of +1. Fixed rounding of Ascent/Descent to match TrueType renderer. If you were adding or subtracting to ImFont::DisplayOffset check if your fonts are correctly aligned vertically.
780
 - 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums.
781
 - 2018/02/18 (1.60) - BeginDragDropSource(): temporarily removed the optional mouse_button=0 parameter because it is not really usable in many situations at the moment.
782
 - 2018/02/16 (1.60) - obsoleted the io.RenderDrawListsFn callback, you can call your graphics engine render function after ImGui::Render(). Use ImGui::GetDrawData() to retrieve the ImDrawData* to display.
783
 - 2018/02/07 (1.60) - reorganized context handling to be more explicit,
784
                       - YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
785
                       - removed Shutdown() function, as DestroyContext() serve this purpose.
786
                       - you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance.
787
                       - removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.
788
                       - removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.
789
 - 2018/01/31 (1.60) - moved sample TTF files from extra_fonts/ to misc/fonts/. If you loaded files directly from the imgui repo you may need to update your paths.
790
 - 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
791
 - 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
792
 - 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
793
 - 2017/12/29 (1.60) - removed CalcItemRectClosestPoint() which was weird and not really used by anyone except demo code. If you need it it's easy to replicate on your side.
794
 - 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
795
 - 2017/12/21 (1.53) - ImDrawList: renamed style.AntiAliasedShapes to style.AntiAliasedFill for consistency and as a way to explicitly break code that manipulate those flag at runtime. You can now manipulate ImDrawList::Flags
796
 - 2017/12/21 (1.53) - ImDrawList: removed 'bool anti_aliased = true' final parameter of ImDrawList::AddPolyline() and ImDrawList::AddConvexPolyFilled(). Prefer manipulating ImDrawList::Flags if you need to toggle them during the frame.
797
 - 2017/12/14 (1.53) - using the ImGuiWindowFlags_NoScrollWithMouse flag on a child window forwards the mouse wheel event to the parent window, unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set.
798
 - 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).
799
 - 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).
800
                     - obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).
801
 - 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).
802
 - 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).
803
 - 2017/11/27 (1.53) - renamed ImGuiTextBuffer::append() helper to appendf(), appendv() to appendfv(). If you copied the 'Log' demo in your code, it uses appendv() so that needs to be renamed.
804
 - 2017/11/18 (1.53) - Style, Begin: removed ImGuiWindowFlags_ShowBorders window flag. Borders are now fully set up in the ImGuiStyle structure (see e.g. style.FrameBorderSize, style.WindowBorderSize). Use ImGui::ShowStyleEditor() to look them up.
805
                       Please note that the style system will keep evolving (hopefully stabilizing in Q1 2018), and so custom styles will probably subtly break over time. It is recommended you use the StyleColorsClassic(), StyleColorsDark(), StyleColorsLight() functions.
806
 - 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.
807
 - 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
808
 - 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
809
 - 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
810
 - 2017/10/24 (1.52) - renamed IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS to IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS for consistency.
811
 - 2017/10/20 (1.52) - changed IsWindowHovered() default parameters behavior to return false if an item is active in another window (e.g. click-dragging item from another window to this window). You can use the newly introduced IsWindowHovered() flags to requests this specific behavior if you need it.
812
 - 2017/10/20 (1.52) - marked IsItemHoveredRect()/IsMouseHoveringWindow() as obsolete, in favor of using the newly introduced flags for IsItemHovered() and IsWindowHovered(). See https://github.com/ocornut/imgui/issues/1382 for details.
813
                       removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
814
                         IsItemHoveredRect()        --> IsItemHovered(ImGuiHoveredFlags_RectOnly)
815
                         IsMouseHoveringAnyWindow() --> IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
816
                         IsMouseHoveringWindow()    --> IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) [weird, old behavior]
817
 - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
818
 - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
819
 - 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete).
820
 - 2017/09/25 (1.52) - removed SetNextWindowPosCenter() because SetNextWindowPos() now has the optional pivot information to do the same and more. Kept redirection function (will obsolete).
821
 - 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your backend if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)".
822
 - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
823
                     - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
824
                     - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
825
 - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
826
 - 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicily to fix.
827
 - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame type.
828
 - 2017/08/15 (1.51) - changed parameter order for BeginPopupContextWindow() from (const char*,int buttons,bool also_over_items) to (const char*,int buttons,bool also_over_items). Note that most calls relied on default parameters completely.
829
 - 2017/08/13 (1.51) - renamed ImGuiCol_Column to ImGuiCol_Separator, ImGuiCol_ColumnHovered to ImGuiCol_SeparatorHovered, ImGuiCol_ColumnActive to ImGuiCol_SeparatorActive. Kept redirection enums (will obsolete).
830
 - 2017/08/11 (1.51) - renamed ImGuiSetCond_Always to ImGuiCond_Always, ImGuiSetCond_Once to ImGuiCond_Once, ImGuiSetCond_FirstUseEver to ImGuiCond_FirstUseEver, ImGuiSetCond_Appearing to ImGuiCond_Appearing. Kept redirection enums (will obsolete).
831
 - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
832
 - 2017/08/08 (1.51) - removed ColorEditMode() and ImGuiColorEditMode in favor of ImGuiColorEditFlags and parameters to the various Color*() functions. The SetColorEditOptions() allows to initialize default but the user can still change them with right-click context menu.
833
                     - changed prototype of 'ColorEdit4(const char* label, float col[4], bool show_alpha = true)' to 'ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0)', where passing flags = 0x01 is a safe no-op (hello dodgy backward compatibility!). - check and run the demo window, under "Color/Picker Widgets", to understand the various new options.
834
                     - changed prototype of rarely used 'ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)' to 'ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0, 0))'
835
 - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
836
 - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
837
 - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
838
 - 2016/11/06 (1.50) - BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple times to a same child from different locations of the stack id. If that's the case, generate an id with GetID() and use it instead of passing string to BeginChild().
839
 - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
840
 - 2016/09/25 (1.50) - style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc.
841
 - 2016/07/30 (1.50) - SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window. This was sort of always the intent and hopefully, breakage should be minimal.
842
 - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
843
                       If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you, otherwise if <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar.
844
                       This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color:
845
                       ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col) { float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a; return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a); }
846
                       If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color.
847
 - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
848
 - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
849
 - 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the "default_open = true" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen).
850
 - 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDrawList::PushClipRect(Imvec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false). Note that higher-level ImGui::PushClipRect() is preferable because it will clip at logic/widget level, whereas ImDrawList::PushClipRect() only affect your renderer.
851
 - 2016/04/03 (1.48) - removed style.WindowFillAlphaDefault setting which was redundant. Bake default BG alpha inside style.Colors[ImGuiCol_WindowBg] and all other Bg color values. (ref GitHub issue #337).
852
 - 2016/04/03 (1.48) - renamed ImGuiCol_TooltipBg to ImGuiCol_PopupBg, used by popups/menus and tooltips. popups/menus were previously using ImGuiCol_WindowBg. (ref github issue #337)
853
 - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
854
 - 2016/03/02 (1.48) - InputText() completion/history/always callbacks: if you modify the text buffer manually (without using DeleteChars()/InsertChars() helper) you need to maintain the BufTextLen field. added an assert.
855
 - 2016/01/23 (1.48) - fixed not honoring exact width passed to PushItemWidth(), previously it would add extra FramePadding.x*2 over that width. if you had manual pixel-perfect alignment in place it might affect you.
856
 - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
857
 - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
858
 - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
859
                       GetCursorPos()/SetCursorPos() functions now include the scrolled amount. It shouldn't affect the majority of users, but take note that SetCursorPosX(100.0f) puts you at +100 from the starting x position which may include scrolling, not at +100 from the window left side.
860
                       GetContentRegionMax()/GetWindowContentRegionMin()/GetWindowContentRegionMax() functions allow include the scrolled amount. Typically those were used in cases where no scrolling would happen so it may not be a problem, but watch out!
861
 - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
862
 - 2015/08/05 (1.44) - split imgui.cpp into extra files: imgui_demo.cpp imgui_draw.cpp imgui_internal.h that you need to add to your project.
863
 - 2015/07/18 (1.44) - fixed angles in ImDrawList::PathArcTo(), PathArcToFast() (introduced in 1.43) being off by an extra PI for no justifiable reason
864
 - 2015/07/14 (1.43) - add new ImFontAtlas::AddFont() API. For the old AddFont***, moved the 'font_no' parameter of ImFontAtlas::AddFont** functions to the ImFontConfig structure.
865
                       you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
866
 - 2015/07/08 (1.43) - switched rendering data to use indexed rendering. this is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marginal cost.
867
                       this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
868
                     - if you are using a vanilla copy of one of the imgui_impl_XXX.cpp provided in the example, you just need to update your copy and you can ignore the rest.
869
                     - the signature of the io.RenderDrawListsFn handler has changed!
870
                       old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
871
                       new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
872
                         parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'
873
                         ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new.
874
                         ImDrawCmd:  'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'.
875
                     - each ImDrawList now contains both a vertex buffer and an index buffer. For each command, render ElemCount/3 triangles using indices from the index buffer.
876
                     - if you REALLY cannot render indexed primitives, you can call the draw_data->DeIndexAllBuffers() method to de-index the buffers. This is slow and a waste of CPU/GPU. Prefer using indexed rendering!
877
                     - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
878
 - 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
879
 - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
880
 - 2015/07/02 (1.42) - renamed GetScrollPosY() to GetScrollY(). Necessary to reduce confusion along with other scrolling functions, because positions (e.g. cursor position) are not equivalent to scrolling amount.
881
 - 2015/06/14 (1.41) - changed ImageButton() default bg_col parameter from (0,0,0,1) (black) to (0,0,0,0) (transparent) - makes a difference when texture have transparence
882
 - 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely used. Sorry!
883
 - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
884
 - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
885
 - 2015/05/27 (1.40) - removed the third 'repeat_if_held' parameter from Button() - sorry! it was rarely used and inconsistent. Use PushButtonRepeat(true) / PopButtonRepeat() to enable repeat on desired buttons.
886
 - 2015/05/11 (1.40) - changed BeginPopup() API, takes a string identifier instead of a bool. ImGui needs to manage the open/closed state of popups. Call OpenPopup() to actually set the "open" state of a popup. BeginPopup() returns true if the popup is opened.
887
 - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
888
 - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
889
 - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
890
 - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
891
 - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
892
 - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
893
 - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
894
 - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
895
 - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
896
 - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
897
 - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
898
 - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
899
 - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
900
 - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
901
 - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
902
 - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
903
 - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
904
 - 2015/01/11 (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
905
                       - old:  const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); [..Upload texture to GPU..];
906
                       - new:  unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); [..Upload texture to GPU..]; io.Fonts->SetTexID(YourTexIdentifier);
907
                       you now have more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs. It is now recommended that you sample the font texture with bilinear interpolation.
908
 - 2015/01/11 (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to call io.Fonts->SetTexID()
909
 - 2015/01/11 (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
910
 - 2015/01/11 (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
911
 - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
912
 - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
913
 - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
914
 - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
915
 - 2014/10/02 (1.14) - renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL and imgui_user.cpp to imgui_user.inl (more IDE friendly)
916
 - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
917
 - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
918
 - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
919
 - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
920
 - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
921
 - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
922
923
924
 FREQUENTLY ASKED QUESTIONS (FAQ)
925
 ================================
926
927
 Read all answers online:
928
   https://www.dearimgui.com/faq or https://github.com/ocornut/imgui/blob/master/docs/FAQ.md (same url)
929
 Read all answers locally (with a text editor or ideally a Markdown viewer):
930
   docs/FAQ.md
931
 Some answers are copied down here to facilitate searching in code.
932
933
 Q&A: Basics
934
 ===========
935
936
 Q: Where is the documentation?
937
 A: This library is poorly documented at the moment and expects the user to be acquainted with C/C++.
938
    - Run the examples/ applications and explore them.
939
    - Read Getting Started (https://github.com/ocornut/imgui/wiki/Getting-Started) guide.
940
    - See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function.
941
    - The demo covers most features of Dear ImGui, so you can read the code and see its output.
942
    - See documentation and comments at the top of imgui.cpp + effectively imgui.h.
943
    - 20+ standalone example applications using e.g. OpenGL/DirectX are provided in the
944
      examples/ folder to explain how to integrate Dear ImGui with your own engine/application.
945
    - The Wiki (https://github.com/ocornut/imgui/wiki) has many resources and links.
946
    - The Glossary (https://github.com/ocornut/imgui/wiki/Glossary) page also may be useful.
947
    - Your programming IDE is your friend, find the type or function declaration to find comments
948
      associated with it.
949
950
 Q: What is this library called?
951
 Q: Which version should I get?
952
 >> This library is called "Dear ImGui", please don't call it "ImGui" :)
953
 >> See https://www.dearimgui.com/faq for details.
954
955
 Q&A: Integration
956
 ================
957
958
 Q: How to get started?
959
 A: Read https://github.com/ocornut/imgui/wiki/Getting-Started. Read 'PROGRAMMER GUIDE' above. Read examples/README.txt.
960
961
 Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?
962
 A: You should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
963
 >> See https://www.dearimgui.com/faq for a fully detailed answer. You really want to read this.
964
965
 Q. How can I enable keyboard or gamepad controls?
966
 Q: How can I use this on a machine without mouse, keyboard or screen? (input share, remote display)
967
 Q: I integrated Dear ImGui in my engine and little squares are showing instead of text...
968
 Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around...
969
 Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries...
970
 >> See https://www.dearimgui.com/faq
971
972
 Q&A: Usage
973
 ----------
974
975
 Q: About the ID Stack system..
976
   - Why is my widget not reacting when I click on it?
977
   - How can I have widgets with an empty label?
978
   - How can I have multiple widgets with the same label?
979
   - How can I have multiple windows with the same label?
980
 Q: How can I display an image? What is ImTextureID, how does it work?
981
 Q: How can I use my own math types instead of ImVec2?
982
 Q: How can I interact with standard C++ types (such as std::string and std::vector)?
983
 Q: How can I display custom shapes? (using low-level ImDrawList API)
984
 >> See https://www.dearimgui.com/faq
985
986
 Q&A: Fonts, Text
987
 ================
988
989
 Q: How should I handle DPI in my application?
990
 Q: How can I load a different font than the default?
991
 Q: How can I easily use icons in my application?
992
 Q: How can I load multiple fonts?
993
 Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
994
 >> See https://www.dearimgui.com/faq and https://github.com/ocornut/imgui/blob/master/docs/FONTS.md
995
996
 Q&A: Concerns
997
 =============
998
999
 Q: Who uses Dear ImGui?
1000
 Q: Can you create elaborate/serious tools with Dear ImGui?
1001
 Q: Can you reskin the look of Dear ImGui?
1002
 Q: Why using C++ (as opposed to C)?
1003
 >> See https://www.dearimgui.com/faq
1004
1005
 Q&A: Community
1006
 ==============
1007
1008
 Q: How can I help?
1009
 A: - Businesses: please reach out to "omar AT dearimgui DOT com" if you work in a place using Dear ImGui!
1010
      We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts.
1011
      This is among the most useful thing you can do for Dear ImGui. With increased funding, we sustain and grow work on this project.
1012
      >>> See https://github.com/ocornut/imgui/wiki/Funding
1013
    - Businesses: you can also purchase licenses for the Dear ImGui Automation/Test Engine.
1014
    - If you are experienced with Dear ImGui and C++, look at the GitHub issues, look at the Wiki, and see how you want to help and can help!
1015
    - Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
1016
      You may post screenshot or links in the gallery threads. Visuals are ideal as they inspire other programmers.
1017
      But even without visuals, disclosing your use of dear imgui helps the library grow credibility, and help other teams and programmers with taking decisions.
1018
    - If you have issues or if you need to hack into the library, even if you don't expect any support it is useful that you share your issues (on GitHub or privately).
1019
1020
*/
1021
1022
//-------------------------------------------------------------------------
1023
// [SECTION] INCLUDES
1024
//-------------------------------------------------------------------------
1025
1026
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
1027
#define _CRT_SECURE_NO_WARNINGS
1028
#endif
1029
1030
#ifndef IMGUI_DEFINE_MATH_OPERATORS
1031
#define IMGUI_DEFINE_MATH_OPERATORS
1032
#endif
1033
1034
#include "imgui.h"
1035
#ifndef IMGUI_DISABLE
1036
#include "imgui_internal.h"
1037
1038
// System includes
1039
#include <stdio.h>      // vsnprintf, sscanf, printf
1040
#include <stdint.h>     // intptr_t
1041
1042
// [Windows] On non-Visual Studio compilers, we default to IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS unless explicitly enabled
1043
#if defined(_WIN32) && !defined(_MSC_VER) && !defined(IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
1044
#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
1045
#endif
1046
1047
// [Windows] OS specific includes (optional)
1048
#if defined(_WIN32) && defined(IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) && defined(IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
1049
#define IMGUI_DISABLE_WIN32_FUNCTIONS
1050
#endif
1051
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
1052
#ifndef WIN32_LEAN_AND_MEAN
1053
#define WIN32_LEAN_AND_MEAN
1054
#endif
1055
#ifndef NOMINMAX
1056
#define NOMINMAX
1057
#endif
1058
#ifndef __MINGW32__
1059
#include <Windows.h>        // _wfopen, OpenClipboard
1060
#else
1061
#include <windows.h>
1062
#endif
1063
#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP || WINAPI_FAMILY == WINAPI_FAMILY_GAMES)
1064
// The UWP and GDK Win32 API subsets don't support clipboard nor IME functions
1065
#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
1066
#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
1067
#define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
1068
#endif
1069
#endif
1070
1071
// [Apple] OS specific includes
1072
#if defined(__APPLE__)
1073
#include <TargetConditionals.h>
1074
#endif
1075
1076
// Visual Studio warnings
1077
#ifdef _MSC_VER
1078
#pragma warning (disable: 4127)             // condition expression is constant
1079
#pragma warning (disable: 4996)             // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
1080
#if defined(_MSC_VER) && _MSC_VER >= 1922   // MSVC 2019 16.2 or later
1081
#pragma warning (disable: 5054)             // operator '|': deprecated between enumerations of different types
1082
#endif
1083
#pragma warning (disable: 26451)            // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to an 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2).
1084
#pragma warning (disable: 26495)            // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6).
1085
#pragma warning (disable: 26812)            // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
1086
#endif
1087
1088
// Clang/GCC warnings with -Weverything
1089
#if defined(__clang__)
1090
#if __has_warning("-Wunknown-warning-option")
1091
#pragma clang diagnostic ignored "-Wunknown-warning-option"         // warning: unknown warning group 'xxx'                      // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great!
1092
#endif
1093
#pragma clang diagnostic ignored "-Wunknown-pragmas"                // warning: unknown warning group 'xxx'
1094
#pragma clang diagnostic ignored "-Wold-style-cast"                 // warning: use of old-style cast                            // yes, they are more terse.
1095
#pragma clang diagnostic ignored "-Wfloat-equal"                    // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok.
1096
#pragma clang diagnostic ignored "-Wformat-nonliteral"              // warning: format string is not a string literal            // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code.
1097
#pragma clang diagnostic ignored "-Wexit-time-destructors"          // warning: declaration requires an exit-time destructor     // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals.
1098
#pragma clang diagnostic ignored "-Wglobal-constructors"            // warning: declaration requires a global destructor         // similar to above, not sure what the exact difference is.
1099
#pragma clang diagnostic ignored "-Wsign-conversion"                // warning: implicit conversion changes signedness
1100
#pragma clang diagnostic ignored "-Wformat-pedantic"                // warning: format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic.
1101
#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast"       // warning: cast to 'void *' from smaller integer type 'int'
1102
#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"  // warning: zero as null pointer constant                    // some standard header variations use #define NULL 0
1103
#pragma clang diagnostic ignored "-Wdouble-promotion"               // warning: implicit conversion from 'float' to 'double' when passing argument to function  // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.
1104
#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion"  // warning: implicit conversion from 'xxx' to 'float' may lose precision
1105
#pragma clang diagnostic ignored "-Wunsafe-buffer-usage"            // warning: 'xxx' is an unsafe pointer used for buffer access
1106
#elif defined(__GNUC__)
1107
// We disable -Wpragmas because GCC doesn't provide a has_warning equivalent and some forks/patches may not follow the warning/version association.
1108
#pragma GCC diagnostic ignored "-Wpragmas"                  // warning: unknown option after '#pragma GCC diagnostic' kind
1109
#pragma GCC diagnostic ignored "-Wunused-function"          // warning: 'xxxx' defined but not used
1110
#pragma GCC diagnostic ignored "-Wint-to-pointer-cast"      // warning: cast to pointer from integer of different size
1111
#pragma GCC diagnostic ignored "-Wformat"                   // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
1112
#pragma GCC diagnostic ignored "-Wdouble-promotion"         // warning: implicit conversion from 'float' to 'double' when passing argument to function
1113
#pragma GCC diagnostic ignored "-Wconversion"               // warning: conversion to 'xxxx' from 'xxxx' may alter its value
1114
#pragma GCC diagnostic ignored "-Wformat-nonliteral"        // warning: format not a string literal, format string not checked
1115
#pragma GCC diagnostic ignored "-Wstrict-overflow"          // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
1116
#pragma GCC diagnostic ignored "-Wclass-memaccess"          // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
1117
#endif
1118
1119
// Debug options
1120
187k
#define IMGUI_DEBUG_NAV_SCORING     0   // Display navigation scoring preview when hovering items. Hold CTRL to display for all candidates. CTRL+Arrow to change last direction.
1121
#define IMGUI_DEBUG_NAV_RECTS       0   // Display the reference navigation rectangle for each window
1122
1123
// When using CTRL+TAB (or Gamepad Square+L/R) we delay the visual a little in order to reduce visual noise doing a fast switch.
1124
static const float NAV_WINDOWING_HIGHLIGHT_DELAY            = 0.20f;    // Time before the highlight and screen dimming starts fading in
1125
static const float NAV_WINDOWING_LIST_APPEAR_DELAY          = 0.15f;    // Time before the window list starts to appear
1126
1127
static const float NAV_ACTIVATE_HIGHLIGHT_TIMER             = 0.10f;    // Time to highlight an item activated by a shortcut.
1128
1129
// Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by backend)
1130
static const float WINDOWS_HOVER_PADDING                    = 4.0f;     // Extend outside window for hovering/resizing (maxxed with TouchPadding) and inside windows for borders. Affect FindHoveredWindow().
1131
static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f;    // Reduce visual noise by only highlighting the border after a certain time.
1132
static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER    = 0.70f;    // Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certain time, unless mouse moved.
1133
1134
// Tooltip offset
1135
static const ImVec2 TOOLTIP_DEFAULT_OFFSET = ImVec2(16, 10);            // Multiplied by g.Style.MouseCursorScale
1136
1137
// Docking
1138
static const float DOCKING_TRANSPARENT_PAYLOAD_ALPHA        = 0.50f;    // For use with io.ConfigDockingTransparentPayload. Apply to Viewport _or_ WindowBg in host viewport.
1139
1140
//-------------------------------------------------------------------------
1141
// [SECTION] FORWARD DECLARATIONS
1142
//-------------------------------------------------------------------------
1143
1144
static void             SetCurrentWindow(ImGuiWindow* window);
1145
static ImGuiWindow*     CreateNewWindow(const char* name, ImGuiWindowFlags flags);
1146
static ImVec2           CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window);
1147
1148
static void             AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
1149
1150
// Settings
1151
static void             WindowSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
1152
static void*            WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
1153
static void             WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
1154
static void             WindowSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
1155
static void             WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf);
1156
1157
// Platform Dependents default implementation for IO functions
1158
static const char*      GetClipboardTextFn_DefaultImpl(void* user_data_ctx);
1159
static void             SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text);
1160
static void             PlatformSetImeDataFn_DefaultImpl(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data);
1161
static bool             PlatformOpenInShellFn_DefaultImpl(ImGuiContext* ctx, const char* path);
1162
1163
namespace ImGui
1164
{
1165
// Item
1166
static void             ItemHandleShortcut(ImGuiID id);
1167
1168
// Navigation
1169
static void             NavUpdate();
1170
static void             NavUpdateWindowing();
1171
static void             NavUpdateWindowingOverlay();
1172
static void             NavUpdateCancelRequest();
1173
static void             NavUpdateCreateMoveRequest();
1174
static void             NavUpdateCreateTabbingRequest();
1175
static float            NavUpdatePageUpPageDown();
1176
static inline void      NavUpdateAnyRequestFlag();
1177
static void             NavUpdateCreateWrappingRequest();
1178
static void             NavEndFrame();
1179
static bool             NavScoreItem(ImGuiNavItemData* result);
1180
static void             NavApplyItemToResult(ImGuiNavItemData* result);
1181
static void             NavProcessItem();
1182
static void             NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags);
1183
static ImVec2           NavCalcPreferredRefPos();
1184
static void             NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window);
1185
static ImGuiWindow*     NavRestoreLastChildNavWindow(ImGuiWindow* window);
1186
static void             NavRestoreLayer(ImGuiNavLayer layer);
1187
static int              FindWindowFocusIndex(ImGuiWindow* window);
1188
1189
// Error Checking and Debug Tools
1190
static void             ErrorCheckNewFrameSanityChecks();
1191
static void             ErrorCheckEndFrameSanityChecks();
1192
static void             UpdateDebugToolItemPicker();
1193
static void             UpdateDebugToolStackQueries();
1194
static void             UpdateDebugToolFlashStyleColor();
1195
1196
// Inputs
1197
static void             UpdateKeyboardInputs();
1198
static void             UpdateMouseInputs();
1199
static void             UpdateMouseWheel();
1200
static void             UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt);
1201
1202
// Misc
1203
static void             UpdateSettings();
1204
static int              UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_hovered, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect);
1205
static void             RenderWindowOuterBorders(ImGuiWindow* window);
1206
static void             RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size);
1207
static void             RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open);
1208
static void             RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col);
1209
static void             RenderDimmedBackgrounds();
1210
static void             SetLastItemDataForWindow(ImGuiWindow* window, const ImRect& rect);
1211
1212
// Viewports
1213
const ImGuiID           IMGUI_VIEWPORT_DEFAULT_ID = 0x11111111; // Using an arbitrary constant instead of e.g. ImHashStr("ViewportDefault", 0); so it's easier to spot in the debugger. The exact value doesn't matter.
1214
static ImGuiViewportP*  AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& platform_pos, const ImVec2& size, ImGuiViewportFlags flags);
1215
static void             DestroyViewport(ImGuiViewportP* viewport);
1216
static void             UpdateViewportsNewFrame();
1217
static void             UpdateViewportsEndFrame();
1218
static void             WindowSelectViewport(ImGuiWindow* window);
1219
static void             WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack);
1220
static bool             UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* host_viewport);
1221
static bool             UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window);
1222
static bool             GetWindowAlwaysWantOwnViewport(ImGuiWindow* window);
1223
static int              FindPlatformMonitorForPos(const ImVec2& pos);
1224
static int              FindPlatformMonitorForRect(const ImRect& r);
1225
static void             UpdateViewportPlatformMonitor(ImGuiViewportP* viewport);
1226
1227
}
1228
1229
//-----------------------------------------------------------------------------
1230
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
1231
//-----------------------------------------------------------------------------
1232
1233
// DLL users:
1234
// - Heaps and globals are not shared across DLL boundaries!
1235
// - You will need to call SetCurrentContext() + SetAllocatorFunctions() for each static/DLL boundary you are calling from.
1236
// - Same applies for hot-reloading mechanisms that are reliant on reloading DLL (note that many hot-reloading mechanisms work without DLL).
1237
// - Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility.
1238
// - Confused? In a debugger: add GImGui to your watch window and notice how its value changes depending on your current location (which DLL boundary you are in).
1239
1240
// Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL.
1241
// - ImGui::CreateContext() will automatically set this pointer if it is NULL.
1242
//   Change to a different context by calling ImGui::SetCurrentContext().
1243
// - Important: Dear ImGui functions are not thread-safe because of this pointer.
1244
//   If you want thread-safety to allow N threads to access N different contexts:
1245
//   - Change this variable to use thread local storage so each thread can refer to a different context, in your imconfig.h:
1246
//         struct ImGuiContext;
1247
//         extern thread_local ImGuiContext* MyImGuiTLS;
1248
//         #define GImGui MyImGuiTLS
1249
//     And then define MyImGuiTLS in one of your cpp files. Note that thread_local is a C++11 keyword, earlier C++ uses compiler-specific keyword.
1250
//   - Future development aims to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
1251
//   - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from a different namespace.
1252
// - DLL users: read comments above.
1253
#ifndef GImGui
1254
ImGuiContext*   GImGui = NULL;
1255
#endif
1256
1257
// Memory Allocator functions. Use SetAllocatorFunctions() to change them.
1258
// - You probably don't want to modify that mid-program, and if you use global/static e.g. ImVector<> instances you may need to keep them accessible during program destruction.
1259
// - DLL users: read comments above.
1260
#ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
1261
1.22k
static void*   MallocWrapper(size_t size, void* user_data)    { IM_UNUSED(user_data); return malloc(size); }
1262
1.17k
static void    FreeWrapper(void* ptr, void* user_data)        { IM_UNUSED(user_data); free(ptr); }
1263
#else
1264
static void*   MallocWrapper(size_t size, void* user_data)    { IM_UNUSED(user_data); IM_UNUSED(size); IM_ASSERT(0); return NULL; }
1265
static void    FreeWrapper(void* ptr, void* user_data)        { IM_UNUSED(user_data); IM_UNUSED(ptr); IM_ASSERT(0); }
1266
#endif
1267
static ImGuiMemAllocFunc    GImAllocatorAllocFunc = MallocWrapper;
1268
static ImGuiMemFreeFunc     GImAllocatorFreeFunc = FreeWrapper;
1269
static void*                GImAllocatorUserData = NULL;
1270
1271
//-----------------------------------------------------------------------------
1272
// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
1273
//-----------------------------------------------------------------------------
1274
1275
ImGuiStyle::ImGuiStyle()
1276
1
{
1277
1
    Alpha                       = 1.0f;             // Global alpha applies to everything in Dear ImGui.
1278
1
    DisabledAlpha               = 0.60f;            // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha.
1279
1
    WindowPadding               = ImVec2(8,8);      // Padding within a window
1280
1
    WindowRounding              = 0.0f;             // Radius of window corners rounding. Set to 0.0f to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended.
1281
1
    WindowBorderSize            = 1.0f;             // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1282
1
    WindowMinSize               = ImVec2(32,32);    // Minimum window size
1283
1
    WindowTitleAlign            = ImVec2(0.0f,0.5f);// Alignment for title bar text
1284
1
    WindowMenuButtonPosition    = ImGuiDir_Left;    // Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left.
1285
1
    ChildRounding               = 0.0f;             // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
1286
1
    ChildBorderSize             = 1.0f;             // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1287
1
    PopupRounding               = 0.0f;             // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows
1288
1
    PopupBorderSize             = 1.0f;             // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1289
1
    FramePadding                = ImVec2(4,3);      // Padding within a framed rectangle (used by most widgets)
1290
1
    FrameRounding               = 0.0f;             // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
1291
1
    FrameBorderSize             = 0.0f;             // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.
1292
1
    ItemSpacing                 = ImVec2(8,4);      // Horizontal and vertical spacing between widgets/lines
1293
1
    ItemInnerSpacing            = ImVec2(4,4);      // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
1294
1
    CellPadding                 = ImVec2(4,2);      // Padding within a table cell. Cellpadding.x is locked for entire table. CellPadding.y may be altered between different rows.
1295
1
    TouchExtraPadding           = ImVec2(0,0);      // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much!
1296
1
    IndentSpacing               = 21.0f;            // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
1297
1
    ColumnsMinSpacing           = 6.0f;             // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
1298
1
    ScrollbarSize               = 14.0f;            // Width of the vertical scrollbar, Height of the horizontal scrollbar
1299
1
    ScrollbarRounding           = 9.0f;             // Radius of grab corners rounding for scrollbar
1300
1
    GrabMinSize                 = 12.0f;            // Minimum width/height of a grab box for slider/scrollbar
1301
1
    GrabRounding                = 0.0f;             // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
1302
1
    LogSliderDeadzone           = 4.0f;             // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero.
1303
1
    TabRounding                 = 4.0f;             // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
1304
1
    TabBorderSize               = 0.0f;             // Thickness of border around tabs.
1305
1
    TabMinWidthForCloseButton   = 0.0f;             // Minimum width for close button to appear on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected.
1306
1
    TabBarBorderSize            = 1.0f;             // Thickness of tab-bar separator, which takes on the tab active color to denote focus.
1307
1
    TabBarOverlineSize          = 2.0f;             // Thickness of tab-bar overline, which highlights the selected tab-bar.
1308
1
    TableAngledHeadersAngle     = 35.0f * (IM_PI / 180.0f); // Angle of angled headers (supported values range from -50 degrees to +50 degrees).
1309
1
    TableAngledHeadersTextAlign = ImVec2(0.5f,0.0f);// Alignment of angled headers within the cell
1310
1
    ColorButtonPosition         = ImGuiDir_Right;   // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.
1311
1
    ButtonTextAlign             = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
1312
1
    SelectableTextAlign         = ImVec2(0.0f,0.0f);// Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line.
1313
1
    SeparatorTextBorderSize     = 3.0f;             // Thickness of border in SeparatorText()
1314
1
    SeparatorTextAlign          = ImVec2(0.0f,0.5f);// Alignment of text within the separator. Defaults to (0.0f, 0.5f) (left aligned, center).
1315
1
    SeparatorTextPadding        = ImVec2(20.0f,3.f);// Horizontal offset of text from each edge of the separator + spacing on other axis. Generally small values. .y is recommended to be == FramePadding.y.
1316
1
    DisplayWindowPadding        = ImVec2(19,19);    // Window position are clamped to be visible within the display area or monitors by at least this amount. Only applies to regular windows.
1317
1
    DisplaySafeAreaPadding      = ImVec2(3,3);      // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows.
1318
1
    DockingSeparatorSize        = 2.0f;             // Thickness of resizing border between docked windows
1319
1
    MouseCursorScale            = 1.0f;             // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
1320
1
    AntiAliasedLines            = true;             // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU.
1321
1
    AntiAliasedLinesUseTex      = true;             // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering (NOT point/nearest filtering).
1322
1
    AntiAliasedFill             = true;             // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.).
1323
1
    CurveTessellationTol        = 1.25f;            // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.
1324
1
    CircleTessellationMaxError  = 0.30f;            // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry.
1325
1326
    // Behaviors
1327
1
    HoverStationaryDelay        = 0.15f;            // Delay for IsItemHovered(ImGuiHoveredFlags_Stationary). Time required to consider mouse stationary.
1328
1
    HoverDelayShort             = 0.15f;            // Delay for IsItemHovered(ImGuiHoveredFlags_DelayShort). Usually used along with HoverStationaryDelay.
1329
1
    HoverDelayNormal            = 0.40f;            // Delay for IsItemHovered(ImGuiHoveredFlags_DelayNormal). "
1330
1
    HoverFlagsForTooltipMouse   = ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_AllowWhenDisabled;    // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using mouse.
1331
1
    HoverFlagsForTooltipNav     = ImGuiHoveredFlags_NoSharedDelay | ImGuiHoveredFlags_DelayNormal | ImGuiHoveredFlags_AllowWhenDisabled;  // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using keyboard/gamepad.
1332
1333
    // Default theme
1334
1
    ImGui::StyleColorsDark(this);
1335
1
}
1336
1337
// To scale your entire UI (e.g. if you want your app to use High DPI or generally be DPI aware) you may use this helper function. Scaling the fonts is done separately and is up to you.
1338
// Important: This operation is lossy because we round all sizes to integer. If you need to change your scale multiples, call this over a freshly initialized ImGuiStyle structure rather than scaling multiple times.
1339
void ImGuiStyle::ScaleAllSizes(float scale_factor)
1340
0
{
1341
0
    WindowPadding = ImTrunc(WindowPadding * scale_factor);
1342
0
    WindowRounding = ImTrunc(WindowRounding * scale_factor);
1343
0
    WindowMinSize = ImTrunc(WindowMinSize * scale_factor);
1344
0
    ChildRounding = ImTrunc(ChildRounding * scale_factor);
1345
0
    PopupRounding = ImTrunc(PopupRounding * scale_factor);
1346
0
    FramePadding = ImTrunc(FramePadding * scale_factor);
1347
0
    FrameRounding = ImTrunc(FrameRounding * scale_factor);
1348
0
    ItemSpacing = ImTrunc(ItemSpacing * scale_factor);
1349
0
    ItemInnerSpacing = ImTrunc(ItemInnerSpacing * scale_factor);
1350
0
    CellPadding = ImTrunc(CellPadding * scale_factor);
1351
0
    TouchExtraPadding = ImTrunc(TouchExtraPadding * scale_factor);
1352
0
    IndentSpacing = ImTrunc(IndentSpacing * scale_factor);
1353
0
    ColumnsMinSpacing = ImTrunc(ColumnsMinSpacing * scale_factor);
1354
0
    ScrollbarSize = ImTrunc(ScrollbarSize * scale_factor);
1355
0
    ScrollbarRounding = ImTrunc(ScrollbarRounding * scale_factor);
1356
0
    GrabMinSize = ImTrunc(GrabMinSize * scale_factor);
1357
0
    GrabRounding = ImTrunc(GrabRounding * scale_factor);
1358
0
    LogSliderDeadzone = ImTrunc(LogSliderDeadzone * scale_factor);
1359
0
    TabRounding = ImTrunc(TabRounding * scale_factor);
1360
0
    TabMinWidthForCloseButton = (TabMinWidthForCloseButton != FLT_MAX) ? ImTrunc(TabMinWidthForCloseButton * scale_factor) : FLT_MAX;
1361
0
    TabBarOverlineSize = ImTrunc(TabBarOverlineSize * scale_factor);
1362
0
    SeparatorTextPadding = ImTrunc(SeparatorTextPadding * scale_factor);
1363
0
    DockingSeparatorSize = ImTrunc(DockingSeparatorSize * scale_factor);
1364
0
    DisplayWindowPadding = ImTrunc(DisplayWindowPadding * scale_factor);
1365
0
    DisplaySafeAreaPadding = ImTrunc(DisplaySafeAreaPadding * scale_factor);
1366
0
    MouseCursorScale = ImTrunc(MouseCursorScale * scale_factor);
1367
0
}
1368
1369
ImGuiIO::ImGuiIO()
1370
1
{
1371
    // Most fields are initialized with zero
1372
1
    memset(this, 0, sizeof(*this));
1373
1
    IM_STATIC_ASSERT(IM_ARRAYSIZE(ImGuiIO::MouseDown) == ImGuiMouseButton_COUNT && IM_ARRAYSIZE(ImGuiIO::MouseClicked) == ImGuiMouseButton_COUNT);
1374
1375
    // Settings
1376
1
    ConfigFlags = ImGuiConfigFlags_None;
1377
1
    BackendFlags = ImGuiBackendFlags_None;
1378
1
    DisplaySize = ImVec2(-1.0f, -1.0f);
1379
1
    DeltaTime = 1.0f / 60.0f;
1380
1
    IniSavingRate = 5.0f;
1381
1
    IniFilename = "imgui.ini"; // Important: "imgui.ini" is relative to current working dir, most apps will want to lock this to an absolute path (e.g. same path as executables).
1382
1
    LogFilename = "imgui_log.txt";
1383
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1384
    for (int i = 0; i < ImGuiKey_COUNT; i++)
1385
        KeyMap[i] = -1;
1386
#endif
1387
1
    UserData = NULL;
1388
1389
1
    Fonts = NULL;
1390
1
    FontGlobalScale = 1.0f;
1391
1
    FontDefault = NULL;
1392
1
    FontAllowUserScaling = false;
1393
1
    DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
1394
1395
    // Docking options (when ImGuiConfigFlags_DockingEnable is set)
1396
1
    ConfigDockingNoSplit = false;
1397
1
    ConfigDockingWithShift = false;
1398
1
    ConfigDockingAlwaysTabBar = false;
1399
1
    ConfigDockingTransparentPayload = false;
1400
1401
    // Viewport options (when ImGuiConfigFlags_ViewportsEnable is set)
1402
1
    ConfigViewportsNoAutoMerge = false;
1403
1
    ConfigViewportsNoTaskBarIcon = false;
1404
1
    ConfigViewportsNoDecoration = true;
1405
1
    ConfigViewportsNoDefaultParent = false;
1406
1407
    // Miscellaneous options
1408
1
    MouseDrawCursor = false;
1409
#ifdef __APPLE__
1410
    ConfigMacOSXBehaviors = true;  // Set Mac OS X style defaults based on __APPLE__ compile time flag
1411
#else
1412
1
    ConfigMacOSXBehaviors = false;
1413
1
#endif
1414
1
    ConfigNavSwapGamepadButtons = false;
1415
1
    ConfigInputTrickleEventQueue = true;
1416
1
    ConfigInputTextCursorBlink = true;
1417
1
    ConfigInputTextEnterKeepActive = false;
1418
1
    ConfigDragClickToInputText = false;
1419
1
    ConfigWindowsResizeFromEdges = true;
1420
1
    ConfigWindowsMoveFromTitleBarOnly = false;
1421
1
    ConfigMemoryCompactTimer = 60.0f;
1422
1
    ConfigDebugBeginReturnValueOnce = false;
1423
1
    ConfigDebugBeginReturnValueLoop = false;
1424
1425
    // Inputs Behaviors
1426
1
    MouseDoubleClickTime = 0.30f;
1427
1
    MouseDoubleClickMaxDist = 6.0f;
1428
1
    MouseDragThreshold = 6.0f;
1429
1
    KeyRepeatDelay = 0.275f;
1430
1
    KeyRepeatRate = 0.050f;
1431
1432
    // Platform Functions
1433
    // Note: Initialize() will setup default clipboard/ime handlers.
1434
1
    BackendPlatformName = BackendRendererName = NULL;
1435
1
    BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL;
1436
1
    PlatformOpenInShellUserData = NULL;
1437
1
    PlatformLocaleDecimalPoint = '.';
1438
1439
    // Input (NB: we already have memset zero the entire structure!)
1440
1
    MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1441
1
    MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
1442
1
    MouseSource = ImGuiMouseSource_Mouse;
1443
6
    for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
1444
155
    for (int i = 0; i < IM_ARRAYSIZE(KeysData); i++) { KeysData[i].DownDuration = KeysData[i].DownDurationPrev = -1.0f; }
1445
1
    AppAcceptingEvents = true;
1446
1
    BackendUsingLegacyKeyArrays = (ImS8)-1;
1447
1
    BackendUsingLegacyNavInputArray = true; // assume using legacy array until proven wrong
1448
1
}
1449
1450
// Pass in translated ASCII characters for text input.
1451
// - with glfw you can get those from the callback set in glfwSetCharCallback()
1452
// - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
1453
// FIXME: Should in theory be called "AddCharacterEvent()" to be consistent with new API
1454
void ImGuiIO::AddInputCharacter(unsigned int c)
1455
8.36k
{
1456
8.36k
    IM_ASSERT(Ctx != NULL);
1457
8.36k
    ImGuiContext& g = *Ctx;
1458
8.36k
    if (c == 0 || !AppAcceptingEvents)
1459
639
        return;
1460
1461
7.72k
    ImGuiInputEvent e;
1462
7.72k
    e.Type = ImGuiInputEventType_Text;
1463
7.72k
    e.Source = ImGuiInputSource_Keyboard;
1464
7.72k
    e.EventId = g.InputEventsNextEventId++;
1465
7.72k
    e.Text.Char = c;
1466
7.72k
    g.InputEventsQueue.push_back(e);
1467
7.72k
}
1468
1469
// UTF16 strings use surrogate pairs to encode codepoints >= 0x10000, so
1470
// we should save the high surrogate.
1471
void ImGuiIO::AddInputCharacterUTF16(ImWchar16 c)
1472
7.17k
{
1473
7.17k
    if ((c == 0 && InputQueueSurrogate == 0) || !AppAcceptingEvents)
1474
323
        return;
1475
1476
6.84k
    if ((c & 0xFC00) == 0xD800) // High surrogate, must save
1477
845
    {
1478
845
        if (InputQueueSurrogate != 0)
1479
442
            AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1480
845
        InputQueueSurrogate = c;
1481
845
        return;
1482
845
    }
1483
1484
6.00k
    ImWchar cp = c;
1485
6.00k
    if (InputQueueSurrogate != 0)
1486
345
    {
1487
345
        if ((c & 0xFC00) != 0xDC00) // Invalid low surrogate
1488
242
        {
1489
242
            AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1490
242
        }
1491
103
        else
1492
103
        {
1493
103
#if IM_UNICODE_CODEPOINT_MAX == 0xFFFF
1494
103
            cp = IM_UNICODE_CODEPOINT_INVALID; // Codepoint will not fit in ImWchar
1495
#else
1496
            cp = (ImWchar)(((InputQueueSurrogate - 0xD800) << 10) + (c - 0xDC00) + 0x10000);
1497
#endif
1498
103
        }
1499
1500
345
        InputQueueSurrogate = 0;
1501
345
    }
1502
6.00k
    AddInputCharacter((unsigned)cp);
1503
6.00k
}
1504
1505
void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
1506
37
{
1507
37
    if (!AppAcceptingEvents)
1508
0
        return;
1509
37
    while (*utf8_chars != 0)
1510
0
    {
1511
0
        unsigned int c = 0;
1512
0
        utf8_chars += ImTextCharFromUtf8(&c, utf8_chars, NULL);
1513
0
        AddInputCharacter(c);
1514
0
    }
1515
37
}
1516
1517
// Clear all incoming events.
1518
void ImGuiIO::ClearEventsQueue()
1519
0
{
1520
0
    IM_ASSERT(Ctx != NULL);
1521
0
    ImGuiContext& g = *Ctx;
1522
0
    g.InputEventsQueue.clear();
1523
0
}
1524
1525
// Clear current keyboard/gamepad state + current frame text input buffer. Equivalent to releasing all keys/buttons.
1526
void ImGuiIO::ClearInputKeys()
1527
13.6k
{
1528
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1529
    memset(KeysDown, 0, sizeof(KeysDown));
1530
#endif
1531
2.12M
    for (int n = 0; n < IM_ARRAYSIZE(KeysData); n++)
1532
2.10M
    {
1533
2.10M
        if (ImGui::IsMouseKey((ImGuiKey)(n + ImGuiKey_KeysData_OFFSET)))
1534
95.8k
            continue;
1535
2.01M
        KeysData[n].Down             = false;
1536
2.01M
        KeysData[n].DownDuration     = -1.0f;
1537
2.01M
        KeysData[n].DownDurationPrev = -1.0f;
1538
2.01M
    }
1539
13.6k
    KeyCtrl = KeyShift = KeyAlt = KeySuper = false;
1540
13.6k
    KeyMods = ImGuiMod_None;
1541
13.6k
    InputQueueCharacters.resize(0); // Behavior of old ClearInputCharacters().
1542
13.6k
}
1543
1544
void ImGuiIO::ClearInputMouse()
1545
958
{
1546
7.66k
    for (ImGuiKey key = ImGuiKey_Mouse_BEGIN; key < ImGuiKey_Mouse_END; key = (ImGuiKey)(key + 1))
1547
6.70k
    {
1548
6.70k
        ImGuiKeyData* key_data = &KeysData[key - ImGuiKey_KeysData_OFFSET];
1549
6.70k
        key_data->Down = false;
1550
6.70k
        key_data->DownDuration = -1.0f;
1551
6.70k
        key_data->DownDurationPrev = -1.0f;
1552
6.70k
    }
1553
958
    MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1554
5.74k
    for (int n = 0; n < IM_ARRAYSIZE(MouseDown); n++)
1555
4.79k
    {
1556
4.79k
        MouseDown[n] = false;
1557
4.79k
        MouseDownDuration[n] = MouseDownDurationPrev[n] = -1.0f;
1558
4.79k
    }
1559
958
    MouseWheel = MouseWheelH = 0.0f;
1560
958
}
1561
1562
// Removed this as it is ambiguous/misleading and generally incorrect to use with the existence of a higher-level input queue.
1563
// Current frame character buffer is now also cleared by ClearInputKeys().
1564
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
1565
void ImGuiIO::ClearInputCharacters()
1566
{
1567
    InputQueueCharacters.resize(0);
1568
}
1569
#endif
1570
1571
static ImGuiInputEvent* FindLatestInputEvent(ImGuiContext* ctx, ImGuiInputEventType type, int arg = -1)
1572
29.6k
{
1573
29.6k
    ImGuiContext& g = *ctx;
1574
45.0k
    for (int n = g.InputEventsQueue.Size - 1; n >= 0; n--)
1575
27.7k
    {
1576
27.7k
        ImGuiInputEvent* e = &g.InputEventsQueue[n];
1577
27.7k
        if (e->Type != type)
1578
7.32k
            continue;
1579
20.3k
        if (type == ImGuiInputEventType_Key && e->Key.Key != arg)
1580
2.92k
            continue;
1581
17.4k
        if (type == ImGuiInputEventType_MouseButton && e->MouseButton.Button != arg)
1582
5.19k
            continue;
1583
12.2k
        return e;
1584
17.4k
    }
1585
17.3k
    return NULL;
1586
29.6k
}
1587
1588
// Queue a new key down/up event.
1589
// - ImGuiKey key:       Translated key (as in, generally ImGuiKey_A matches the key end-user would use to emit an 'A' character)
1590
// - bool down:          Is the key down? use false to signify a key release.
1591
// - float analog_value: 0.0f..1.0f
1592
// IMPORTANT: THIS FUNCTION AND OTHER "ADD" GRABS THE CONTEXT FROM OUR INSTANCE.
1593
// WE NEED TO ENSURE THAT ALL FUNCTION CALLS ARE FULFILLING THIS, WHICH IS WHY GetKeyData() HAS AN EXPLICIT CONTEXT.
1594
void ImGuiIO::AddKeyAnalogEvent(ImGuiKey key, bool down, float analog_value)
1595
9.04k
{
1596
    //if (e->Down) { IMGUI_DEBUG_LOG_IO("AddKeyEvent() Key='%s' %d, NativeKeycode = %d, NativeScancode = %d\n", ImGui::GetKeyName(e->Key), e->Down, e->NativeKeycode, e->NativeScancode); }
1597
9.04k
    IM_ASSERT(Ctx != NULL);
1598
9.04k
    if (key == ImGuiKey_None || !AppAcceptingEvents)
1599
0
        return;
1600
9.04k
    ImGuiContext& g = *Ctx;
1601
9.04k
    IM_ASSERT(ImGui::IsNamedKeyOrMod(key)); // Backend needs to pass a valid ImGuiKey_ constant. 0..511 values are legacy native key codes which are not accepted by this API.
1602
9.04k
    IM_ASSERT(ImGui::IsAliasKey(key) == false); // Backend cannot submit ImGuiKey_MouseXXX values they are automatically inferred from AddMouseXXX() events.
1603
1604
    // MacOS: swap Cmd(Super) and Ctrl
1605
9.04k
    if (g.IO.ConfigMacOSXBehaviors)
1606
0
    {
1607
0
        if (key == ImGuiMod_Super)          { key = ImGuiMod_Ctrl; }
1608
0
        else if (key == ImGuiMod_Ctrl)      { key = ImGuiMod_Super; }
1609
0
        else if (key == ImGuiKey_LeftSuper) { key = ImGuiKey_LeftCtrl; }
1610
0
        else if (key == ImGuiKey_RightSuper){ key = ImGuiKey_RightCtrl; }
1611
0
        else if (key == ImGuiKey_LeftCtrl)  { key = ImGuiKey_LeftSuper; }
1612
0
        else if (key == ImGuiKey_RightCtrl) { key = ImGuiKey_RightSuper; }
1613
0
    }
1614
1615
    // Verify that backend isn't mixing up using new io.AddKeyEvent() api and old io.KeysDown[] + io.KeyMap[] data.
1616
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1617
    IM_ASSERT((BackendUsingLegacyKeyArrays == -1 || BackendUsingLegacyKeyArrays == 0) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
1618
    if (BackendUsingLegacyKeyArrays == -1)
1619
        for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
1620
            IM_ASSERT(KeyMap[n] == -1 && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
1621
    BackendUsingLegacyKeyArrays = 0;
1622
#endif
1623
9.04k
    if (ImGui::IsGamepadKey(key))
1624
107
        BackendUsingLegacyNavInputArray = false;
1625
1626
    // Filter duplicate (in particular: key mods and gamepad analog values are commonly spammed)
1627
9.04k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Key, (int)key);
1628
9.04k
    const ImGuiKeyData* key_data = ImGui::GetKeyData(&g, key);
1629
9.04k
    const bool latest_key_down = latest_event ? latest_event->Key.Down : key_data->Down;
1630
9.04k
    const float latest_key_analog = latest_event ? latest_event->Key.AnalogValue : key_data->AnalogValue;
1631
9.04k
    if (latest_key_down == down && latest_key_analog == analog_value)
1632
2.25k
        return;
1633
1634
    // Add event
1635
6.79k
    ImGuiInputEvent e;
1636
6.79k
    e.Type = ImGuiInputEventType_Key;
1637
6.79k
    e.Source = ImGui::IsGamepadKey(key) ? ImGuiInputSource_Gamepad : ImGuiInputSource_Keyboard;
1638
6.79k
    e.EventId = g.InputEventsNextEventId++;
1639
6.79k
    e.Key.Key = key;
1640
6.79k
    e.Key.Down = down;
1641
6.79k
    e.Key.AnalogValue = analog_value;
1642
6.79k
    g.InputEventsQueue.push_back(e);
1643
6.79k
}
1644
1645
void ImGuiIO::AddKeyEvent(ImGuiKey key, bool down)
1646
8.44k
{
1647
8.44k
    if (!AppAcceptingEvents)
1648
0
        return;
1649
8.44k
    AddKeyAnalogEvent(key, down, down ? 1.0f : 0.0f);
1650
8.44k
}
1651
1652
// [Optional] Call after AddKeyEvent().
1653
// Specify native keycode, scancode + Specify index for legacy <1.87 IsKeyXXX() functions with native indices.
1654
// If you are writing a backend in 2022 or don't use IsKeyXXX() with native values that are not ImGuiKey values, you can avoid calling this.
1655
void ImGuiIO::SetKeyEventNativeData(ImGuiKey key, int native_keycode, int native_scancode, int native_legacy_index)
1656
0
{
1657
0
    if (key == ImGuiKey_None)
1658
0
        return;
1659
0
    IM_ASSERT(ImGui::IsNamedKey(key)); // >= 512
1660
0
    IM_ASSERT(native_legacy_index == -1 || ImGui::IsLegacyKey((ImGuiKey)native_legacy_index)); // >= 0 && <= 511
1661
0
    IM_UNUSED(native_keycode);  // Yet unused
1662
0
    IM_UNUSED(native_scancode); // Yet unused
1663
1664
    // Build native->imgui map so old user code can still call key functions with native 0..511 values.
1665
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1666
    const int legacy_key = (native_legacy_index != -1) ? native_legacy_index : native_keycode;
1667
    if (!ImGui::IsLegacyKey((ImGuiKey)legacy_key))
1668
        return;
1669
    KeyMap[legacy_key] = key;
1670
    KeyMap[key] = legacy_key;
1671
#else
1672
0
    IM_UNUSED(key);
1673
0
    IM_UNUSED(native_legacy_index);
1674
0
#endif
1675
0
}
1676
1677
// Set master flag for accepting key/mouse/text events (default to true). Useful if you have native dialog boxes that are interrupting your application loop/refresh, and you want to disable events being queued while your app is frozen.
1678
void ImGuiIO::SetAppAcceptingEvents(bool accepting_events)
1679
0
{
1680
0
    AppAcceptingEvents = accepting_events;
1681
0
}
1682
1683
// Queue a mouse move event
1684
void ImGuiIO::AddMousePosEvent(float x, float y)
1685
4.23k
{
1686
4.23k
    IM_ASSERT(Ctx != NULL);
1687
4.23k
    ImGuiContext& g = *Ctx;
1688
4.23k
    if (!AppAcceptingEvents)
1689
0
        return;
1690
1691
    // Apply same flooring as UpdateMouseInputs()
1692
4.23k
    ImVec2 pos((x > -FLT_MAX) ? ImFloor(x) : x, (y > -FLT_MAX) ? ImFloor(y) : y);
1693
1694
    // Filter duplicate
1695
4.23k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MousePos);
1696
4.23k
    const ImVec2 latest_pos = latest_event ? ImVec2(latest_event->MousePos.PosX, latest_event->MousePos.PosY) : g.IO.MousePos;
1697
4.23k
    if (latest_pos.x == pos.x && latest_pos.y == pos.y)
1698
1.85k
        return;
1699
1700
2.37k
    ImGuiInputEvent e;
1701
2.37k
    e.Type = ImGuiInputEventType_MousePos;
1702
2.37k
    e.Source = ImGuiInputSource_Mouse;
1703
2.37k
    e.EventId = g.InputEventsNextEventId++;
1704
2.37k
    e.MousePos.PosX = pos.x;
1705
2.37k
    e.MousePos.PosY = pos.y;
1706
2.37k
    e.MousePos.MouseSource = g.InputEventsNextMouseSource;
1707
2.37k
    g.InputEventsQueue.push_back(e);
1708
2.37k
}
1709
1710
void ImGuiIO::AddMouseButtonEvent(int mouse_button, bool down)
1711
13.7k
{
1712
13.7k
    IM_ASSERT(Ctx != NULL);
1713
13.7k
    ImGuiContext& g = *Ctx;
1714
13.7k
    IM_ASSERT(mouse_button >= 0 && mouse_button < ImGuiMouseButton_COUNT);
1715
13.7k
    if (!AppAcceptingEvents)
1716
0
        return;
1717
1718
    // On MacOS X: Convert Ctrl(Super)+Left click into Right-click: handle held button.
1719
13.7k
    if (ConfigMacOSXBehaviors && mouse_button == 0 && MouseCtrlLeftAsRightClick)
1720
0
    {
1721
        // Order of both statements matterns: this event will still release mouse button 1
1722
0
        mouse_button = 1;
1723
0
        if (!down)
1724
0
            MouseCtrlLeftAsRightClick = false;
1725
0
    }
1726
1727
    // Filter duplicate
1728
13.7k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MouseButton, (int)mouse_button);
1729
13.7k
    const bool latest_button_down = latest_event ? latest_event->MouseButton.Down : g.IO.MouseDown[mouse_button];
1730
13.7k
    if (latest_button_down == down)
1731
4.05k
        return;
1732
1733
    // On MacOS X: Convert Ctrl(Super)+Left click into Right-click.
1734
    // - Note that this is actual physical Ctrl which is ImGuiMod_Super for us.
1735
    // - At this point we want from !down to down, so this is handling the initial press.
1736
9.70k
    if (ConfigMacOSXBehaviors && mouse_button == 0 && down)
1737
0
    {
1738
0
        const ImGuiInputEvent* latest_super_event = FindLatestInputEvent(&g, ImGuiInputEventType_Key, (int)ImGuiMod_Super);
1739
0
        if (latest_super_event ? latest_super_event->Key.Down : g.IO.KeySuper)
1740
0
        {
1741
0
            IMGUI_DEBUG_LOG_IO("[io] Super+Left Click aliased into Right Click\n");
1742
0
            MouseCtrlLeftAsRightClick = true;
1743
0
            AddMouseButtonEvent(1, true); // This is just quicker to write that passing through, as we need to filter duplicate again.
1744
0
            return;
1745
0
        }
1746
0
    }
1747
1748
9.70k
    ImGuiInputEvent e;
1749
9.70k
    e.Type = ImGuiInputEventType_MouseButton;
1750
9.70k
    e.Source = ImGuiInputSource_Mouse;
1751
9.70k
    e.EventId = g.InputEventsNextEventId++;
1752
9.70k
    e.MouseButton.Button = mouse_button;
1753
9.70k
    e.MouseButton.Down = down;
1754
9.70k
    e.MouseButton.MouseSource = g.InputEventsNextMouseSource;
1755
9.70k
    g.InputEventsQueue.push_back(e);
1756
9.70k
}
1757
1758
// Queue a mouse wheel event (some mouse/API may only have a Y component)
1759
void ImGuiIO::AddMouseWheelEvent(float wheel_x, float wheel_y)
1760
2.34k
{
1761
2.34k
    IM_ASSERT(Ctx != NULL);
1762
2.34k
    ImGuiContext& g = *Ctx;
1763
1764
    // Filter duplicate (unlike most events, wheel values are relative and easy to filter)
1765
2.34k
    if (!AppAcceptingEvents || (wheel_x == 0.0f && wheel_y == 0.0f))
1766
24
        return;
1767
1768
2.32k
    ImGuiInputEvent e;
1769
2.32k
    e.Type = ImGuiInputEventType_MouseWheel;
1770
2.32k
    e.Source = ImGuiInputSource_Mouse;
1771
2.32k
    e.EventId = g.InputEventsNextEventId++;
1772
2.32k
    e.MouseWheel.WheelX = wheel_x;
1773
2.32k
    e.MouseWheel.WheelY = wheel_y;
1774
2.32k
    e.MouseWheel.MouseSource = g.InputEventsNextMouseSource;
1775
2.32k
    g.InputEventsQueue.push_back(e);
1776
2.32k
}
1777
1778
// This is not a real event, the data is latched in order to be stored in actual Mouse events.
1779
// This is so that duplicate events (e.g. Windows sending extraneous WM_MOUSEMOVE) gets filtered and are not leading to actual source changes.
1780
void ImGuiIO::AddMouseSourceEvent(ImGuiMouseSource source)
1781
0
{
1782
0
    IM_ASSERT(Ctx != NULL);
1783
0
    ImGuiContext& g = *Ctx;
1784
0
    g.InputEventsNextMouseSource = source;
1785
0
}
1786
1787
void ImGuiIO::AddMouseViewportEvent(ImGuiID viewport_id)
1788
0
{
1789
0
    IM_ASSERT(Ctx != NULL);
1790
0
    ImGuiContext& g = *Ctx;
1791
    //IM_ASSERT(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport);
1792
0
    if (!AppAcceptingEvents)
1793
0
        return;
1794
1795
    // Filter duplicate
1796
0
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MouseViewport);
1797
0
    const ImGuiID latest_viewport_id = latest_event ? latest_event->MouseViewport.HoveredViewportID : g.IO.MouseHoveredViewport;
1798
0
    if (latest_viewport_id == viewport_id)
1799
0
        return;
1800
1801
0
    ImGuiInputEvent e;
1802
0
    e.Type = ImGuiInputEventType_MouseViewport;
1803
0
    e.Source = ImGuiInputSource_Mouse;
1804
0
    e.MouseViewport.HoveredViewportID = viewport_id;
1805
0
    g.InputEventsQueue.push_back(e);
1806
0
}
1807
1808
void ImGuiIO::AddFocusEvent(bool focused)
1809
2.57k
{
1810
2.57k
    IM_ASSERT(Ctx != NULL);
1811
2.57k
    ImGuiContext& g = *Ctx;
1812
1813
    // Filter duplicate
1814
2.57k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Focus);
1815
2.57k
    const bool latest_focused = latest_event ? latest_event->AppFocused.Focused : !g.IO.AppFocusLost;
1816
2.57k
    if (latest_focused == focused || (ConfigDebugIgnoreFocusLoss && !focused))
1817
1.18k
        return;
1818
1819
1.39k
    ImGuiInputEvent e;
1820
1.39k
    e.Type = ImGuiInputEventType_Focus;
1821
1.39k
    e.EventId = g.InputEventsNextEventId++;
1822
1.39k
    e.AppFocused.Focused = focused;
1823
1.39k
    g.InputEventsQueue.push_back(e);
1824
1.39k
}
1825
1826
//-----------------------------------------------------------------------------
1827
// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
1828
//-----------------------------------------------------------------------------
1829
1830
ImVec2 ImBezierCubicClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments)
1831
0
{
1832
0
    IM_ASSERT(num_segments > 0); // Use ImBezierCubicClosestPointCasteljau()
1833
0
    ImVec2 p_last = p1;
1834
0
    ImVec2 p_closest;
1835
0
    float p_closest_dist2 = FLT_MAX;
1836
0
    float t_step = 1.0f / (float)num_segments;
1837
0
    for (int i_step = 1; i_step <= num_segments; i_step++)
1838
0
    {
1839
0
        ImVec2 p_current = ImBezierCubicCalc(p1, p2, p3, p4, t_step * i_step);
1840
0
        ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
1841
0
        float dist2 = ImLengthSqr(p - p_line);
1842
0
        if (dist2 < p_closest_dist2)
1843
0
        {
1844
0
            p_closest = p_line;
1845
0
            p_closest_dist2 = dist2;
1846
0
        }
1847
0
        p_last = p_current;
1848
0
    }
1849
0
    return p_closest;
1850
0
}
1851
1852
// Closely mimics PathBezierToCasteljau() in imgui_draw.cpp
1853
static void ImBezierCubicClosestPointCasteljauStep(const ImVec2& p, ImVec2& p_closest, ImVec2& p_last, float& p_closest_dist2, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level)
1854
0
{
1855
0
    float dx = x4 - x1;
1856
0
    float dy = y4 - y1;
1857
0
    float d2 = ((x2 - x4) * dy - (y2 - y4) * dx);
1858
0
    float d3 = ((x3 - x4) * dy - (y3 - y4) * dx);
1859
0
    d2 = (d2 >= 0) ? d2 : -d2;
1860
0
    d3 = (d3 >= 0) ? d3 : -d3;
1861
0
    if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy))
1862
0
    {
1863
0
        ImVec2 p_current(x4, y4);
1864
0
        ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
1865
0
        float dist2 = ImLengthSqr(p - p_line);
1866
0
        if (dist2 < p_closest_dist2)
1867
0
        {
1868
0
            p_closest = p_line;
1869
0
            p_closest_dist2 = dist2;
1870
0
        }
1871
0
        p_last = p_current;
1872
0
    }
1873
0
    else if (level < 10)
1874
0
    {
1875
0
        float x12 = (x1 + x2)*0.5f,       y12 = (y1 + y2)*0.5f;
1876
0
        float x23 = (x2 + x3)*0.5f,       y23 = (y2 + y3)*0.5f;
1877
0
        float x34 = (x3 + x4)*0.5f,       y34 = (y3 + y4)*0.5f;
1878
0
        float x123 = (x12 + x23)*0.5f,    y123 = (y12 + y23)*0.5f;
1879
0
        float x234 = (x23 + x34)*0.5f,    y234 = (y23 + y34)*0.5f;
1880
0
        float x1234 = (x123 + x234)*0.5f, y1234 = (y123 + y234)*0.5f;
1881
0
        ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1);
1882
0
        ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1);
1883
0
    }
1884
0
}
1885
1886
// tess_tol is generally the same value you would find in ImGui::GetStyle().CurveTessellationTol
1887
// Because those ImXXX functions are lower-level than ImGui:: we cannot access this value automatically.
1888
ImVec2 ImBezierCubicClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol)
1889
0
{
1890
0
    IM_ASSERT(tess_tol > 0.0f);
1891
0
    ImVec2 p_last = p1;
1892
0
    ImVec2 p_closest;
1893
0
    float p_closest_dist2 = FLT_MAX;
1894
0
    ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, tess_tol, 0);
1895
0
    return p_closest;
1896
0
}
1897
1898
ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
1899
0
{
1900
0
    ImVec2 ap = p - a;
1901
0
    ImVec2 ab_dir = b - a;
1902
0
    float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
1903
0
    if (dot < 0.0f)
1904
0
        return a;
1905
0
    float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y;
1906
0
    if (dot > ab_len_sqr)
1907
0
        return b;
1908
0
    return a + ab_dir * dot / ab_len_sqr;
1909
0
}
1910
1911
bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1912
0
{
1913
0
    bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
1914
0
    bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
1915
0
    bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
1916
0
    return ((b1 == b2) && (b2 == b3));
1917
0
}
1918
1919
void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)
1920
0
{
1921
0
    ImVec2 v0 = b - a;
1922
0
    ImVec2 v1 = c - a;
1923
0
    ImVec2 v2 = p - a;
1924
0
    const float denom = v0.x * v1.y - v1.x * v0.y;
1925
0
    out_v = (v2.x * v1.y - v1.x * v2.y) / denom;
1926
0
    out_w = (v0.x * v2.y - v2.x * v0.y) / denom;
1927
0
    out_u = 1.0f - out_v - out_w;
1928
0
}
1929
1930
ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1931
0
{
1932
0
    ImVec2 proj_ab = ImLineClosestPoint(a, b, p);
1933
0
    ImVec2 proj_bc = ImLineClosestPoint(b, c, p);
1934
0
    ImVec2 proj_ca = ImLineClosestPoint(c, a, p);
1935
0
    float dist2_ab = ImLengthSqr(p - proj_ab);
1936
0
    float dist2_bc = ImLengthSqr(p - proj_bc);
1937
0
    float dist2_ca = ImLengthSqr(p - proj_ca);
1938
0
    float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca));
1939
0
    if (m == dist2_ab)
1940
0
        return proj_ab;
1941
0
    if (m == dist2_bc)
1942
0
        return proj_bc;
1943
0
    return proj_ca;
1944
0
}
1945
1946
//-----------------------------------------------------------------------------
1947
// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
1948
//-----------------------------------------------------------------------------
1949
1950
// Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more.
1951
int ImStricmp(const char* str1, const char* str2)
1952
0
{
1953
0
    int d;
1954
0
    while ((d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; }
1955
0
    return d;
1956
0
}
1957
1958
int ImStrnicmp(const char* str1, const char* str2, size_t count)
1959
0
{
1960
0
    int d = 0;
1961
0
    while (count > 0 && (d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; count--; }
1962
0
    return d;
1963
0
}
1964
1965
void ImStrncpy(char* dst, const char* src, size_t count)
1966
0
{
1967
0
    if (count < 1)
1968
0
        return;
1969
0
    if (count > 1)
1970
0
        strncpy(dst, src, count - 1);
1971
0
    dst[count - 1] = 0;
1972
0
}
1973
1974
char* ImStrdup(const char* str)
1975
3
{
1976
3
    size_t len = strlen(str);
1977
3
    void* buf = IM_ALLOC(len + 1);
1978
3
    return (char*)memcpy(buf, (const void*)str, len + 1);
1979
3
}
1980
1981
char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)
1982
0
{
1983
0
    size_t dst_buf_size = p_dst_size ? *p_dst_size : strlen(dst) + 1;
1984
0
    size_t src_size = strlen(src) + 1;
1985
0
    if (dst_buf_size < src_size)
1986
0
    {
1987
0
        IM_FREE(dst);
1988
0
        dst = (char*)IM_ALLOC(src_size);
1989
0
        if (p_dst_size)
1990
0
            *p_dst_size = src_size;
1991
0
    }
1992
0
    return (char*)memcpy(dst, (const void*)src, src_size);
1993
0
}
1994
1995
const char* ImStrchrRange(const char* str, const char* str_end, char c)
1996
0
{
1997
0
    const char* p = (const char*)memchr(str, (int)c, str_end - str);
1998
0
    return p;
1999
0
}
2000
2001
int ImStrlenW(const ImWchar* str)
2002
0
{
2003
    //return (int)wcslen((const wchar_t*)str);  // FIXME-OPT: Could use this when wchar_t are 16-bit
2004
0
    int n = 0;
2005
0
    while (*str++) n++;
2006
0
    return n;
2007
0
}
2008
2009
// Find end-of-line. Return pointer will point to either first \n, either str_end.
2010
const char* ImStreolRange(const char* str, const char* str_end)
2011
0
{
2012
0
    const char* p = (const char*)memchr(str, '\n', str_end - str);
2013
0
    return p ? p : str_end;
2014
0
}
2015
2016
const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line
2017
0
{
2018
0
    while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
2019
0
        buf_mid_line--;
2020
0
    return buf_mid_line;
2021
0
}
2022
2023
const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
2024
0
{
2025
0
    if (!needle_end)
2026
0
        needle_end = needle + strlen(needle);
2027
2028
0
    const char un0 = (char)ImToUpper(*needle);
2029
0
    while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
2030
0
    {
2031
0
        if (ImToUpper(*haystack) == un0)
2032
0
        {
2033
0
            const char* b = needle + 1;
2034
0
            for (const char* a = haystack + 1; b < needle_end; a++, b++)
2035
0
                if (ImToUpper(*a) != ImToUpper(*b))
2036
0
                    break;
2037
0
            if (b == needle_end)
2038
0
                return haystack;
2039
0
        }
2040
0
        haystack++;
2041
0
    }
2042
0
    return NULL;
2043
0
}
2044
2045
// Trim str by offsetting contents when there's leading data + writing a \0 at the trailing position. We use this in situation where the cost is negligible.
2046
void ImStrTrimBlanks(char* buf)
2047
0
{
2048
0
    char* p = buf;
2049
0
    while (p[0] == ' ' || p[0] == '\t')     // Leading blanks
2050
0
        p++;
2051
0
    char* p_start = p;
2052
0
    while (*p != 0)                         // Find end of string
2053
0
        p++;
2054
0
    while (p > p_start && (p[-1] == ' ' || p[-1] == '\t'))  // Trailing blanks
2055
0
        p--;
2056
0
    if (p_start != buf)                     // Copy memory if we had leading blanks
2057
0
        memmove(buf, p_start, p - p_start);
2058
0
    buf[p - p_start] = 0;                   // Zero terminate
2059
0
}
2060
2061
const char* ImStrSkipBlank(const char* str)
2062
0
{
2063
0
    while (str[0] == ' ' || str[0] == '\t')
2064
0
        str++;
2065
0
    return str;
2066
0
}
2067
2068
// A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
2069
// Ideally we would test for only one of those limits at runtime depending on the behavior the vsnprintf(), but trying to deduct it at compile time sounds like a pandora can of worm.
2070
// B) When buf==NULL vsnprintf() will return the output size.
2071
#ifndef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
2072
2073
// We support stb_sprintf which is much faster (see: https://github.com/nothings/stb/blob/master/stb_sprintf.h)
2074
// You may set IMGUI_USE_STB_SPRINTF to use our default wrapper, or set IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
2075
// and setup the wrapper yourself. (FIXME-OPT: Some of our high-level operations such as ImGuiTextBuffer::appendfv() are
2076
// designed using two-passes worst case, which probably could be improved using the stbsp_vsprintfcb() function.)
2077
#ifdef IMGUI_USE_STB_SPRINTF
2078
#ifndef IMGUI_DISABLE_STB_SPRINTF_IMPLEMENTATION
2079
#define STB_SPRINTF_IMPLEMENTATION
2080
#endif
2081
#ifdef IMGUI_STB_SPRINTF_FILENAME
2082
#include IMGUI_STB_SPRINTF_FILENAME
2083
#else
2084
#include "stb_sprintf.h"
2085
#endif
2086
#endif // #ifdef IMGUI_USE_STB_SPRINTF
2087
2088
#if defined(_MSC_VER) && !defined(vsnprintf)
2089
#define vsnprintf _vsnprintf
2090
#endif
2091
2092
int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
2093
1
{
2094
1
    va_list args;
2095
1
    va_start(args, fmt);
2096
#ifdef IMGUI_USE_STB_SPRINTF
2097
    int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
2098
#else
2099
1
    int w = vsnprintf(buf, buf_size, fmt, args);
2100
1
#endif
2101
1
    va_end(args);
2102
1
    if (buf == NULL)
2103
0
        return w;
2104
1
    if (w == -1 || w >= (int)buf_size)
2105
0
        w = (int)buf_size - 1;
2106
1
    buf[w] = 0;
2107
1
    return w;
2108
1
}
2109
2110
int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
2111
23.7k
{
2112
#ifdef IMGUI_USE_STB_SPRINTF
2113
    int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
2114
#else
2115
23.7k
    int w = vsnprintf(buf, buf_size, fmt, args);
2116
23.7k
#endif
2117
23.7k
    if (buf == NULL)
2118
0
        return w;
2119
23.7k
    if (w == -1 || w >= (int)buf_size)
2120
0
        w = (int)buf_size - 1;
2121
23.7k
    buf[w] = 0;
2122
23.7k
    return w;
2123
23.7k
}
2124
#endif // #ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
2125
2126
void ImFormatStringToTempBuffer(const char** out_buf, const char** out_buf_end, const char* fmt, ...)
2127
23.7k
{
2128
23.7k
    va_list args;
2129
23.7k
    va_start(args, fmt);
2130
23.7k
    ImFormatStringToTempBufferV(out_buf, out_buf_end, fmt, args);
2131
23.7k
    va_end(args);
2132
23.7k
}
2133
2134
// FIXME: Should rework API toward allowing multiple in-flight temp buffers (easier and safer for caller)
2135
// by making the caller acquire a temp buffer token, with either explicit or destructor release, e.g.
2136
//  ImGuiTempBufferToken token;
2137
//  ImFormatStringToTempBuffer(token, ...);
2138
void ImFormatStringToTempBufferV(const char** out_buf, const char** out_buf_end, const char* fmt, va_list args)
2139
23.7k
{
2140
23.7k
    ImGuiContext& g = *GImGui;
2141
23.7k
    if (fmt[0] == '%' && fmt[1] == 's' && fmt[2] == 0)
2142
0
    {
2143
0
        const char* buf = va_arg(args, const char*); // Skip formatting when using "%s"
2144
0
        if (buf == NULL)
2145
0
            buf = "(null)";
2146
0
        *out_buf = buf;
2147
0
        if (out_buf_end) { *out_buf_end = buf + strlen(buf); }
2148
0
    }
2149
23.7k
    else if (fmt[0] == '%' && fmt[1] == '.' && fmt[2] == '*' && fmt[3] == 's' && fmt[4] == 0)
2150
0
    {
2151
0
        int buf_len = va_arg(args, int); // Skip formatting when using "%.*s"
2152
0
        const char* buf = va_arg(args, const char*);
2153
0
        if (buf == NULL)
2154
0
        {
2155
0
            buf = "(null)";
2156
0
            buf_len = ImMin(buf_len, 6);
2157
0
        }
2158
0
        *out_buf = buf;
2159
0
        *out_buf_end = buf + buf_len; // Disallow not passing 'out_buf_end' here. User is expected to use it.
2160
0
    }
2161
23.7k
    else
2162
23.7k
    {
2163
23.7k
        int buf_len = ImFormatStringV(g.TempBuffer.Data, g.TempBuffer.Size, fmt, args);
2164
23.7k
        *out_buf = g.TempBuffer.Data;
2165
23.7k
        if (out_buf_end) { *out_buf_end = g.TempBuffer.Data + buf_len; }
2166
23.7k
    }
2167
23.7k
}
2168
2169
// CRC32 needs a 1KB lookup table (not cache friendly)
2170
// Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
2171
// - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
2172
static const ImU32 GCrc32LookupTable[256] =
2173
{
2174
    0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
2175
    0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
2176
    0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
2177
    0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
2178
    0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
2179
    0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
2180
    0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
2181
    0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
2182
    0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
2183
    0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
2184
    0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
2185
    0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
2186
    0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
2187
    0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
2188
    0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
2189
    0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
2190
};
2191
2192
// Known size hash
2193
// It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
2194
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
2195
ImGuiID ImHashData(const void* data_p, size_t data_size, ImGuiID seed)
2196
142k
{
2197
142k
    ImU32 crc = ~seed;
2198
142k
    const unsigned char* data = (const unsigned char*)data_p;
2199
142k
    const ImU32* crc32_lut = GCrc32LookupTable;
2200
711k
    while (data_size-- != 0)
2201
568k
        crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];
2202
142k
    return ~crc;
2203
142k
}
2204
2205
// Zero-terminated string hash, with support for ### to reset back to seed value
2206
// We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
2207
// Because this syntax is rarely used we are optimizing for the common case.
2208
// - If we reach ### in the string we discard the hash so far and reset to the seed.
2209
// - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build)
2210
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
2211
ImGuiID ImHashStr(const char* data_p, size_t data_size, ImGuiID seed)
2212
564k
{
2213
564k
    seed = ~seed;
2214
564k
    ImU32 crc = seed;
2215
564k
    const unsigned char* data = (const unsigned char*)data_p;
2216
564k
    const ImU32* crc32_lut = GCrc32LookupTable;
2217
564k
    if (data_size != 0)
2218
0
    {
2219
0
        while (data_size-- != 0)
2220
0
        {
2221
0
            unsigned char c = *data++;
2222
0
            if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#')
2223
0
                crc = seed;
2224
0
            crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2225
0
        }
2226
0
    }
2227
564k
    else
2228
564k
    {
2229
7.70M
        while (unsigned char c = *data++)
2230
7.14M
        {
2231
7.14M
            if (c == '#' && data[0] == '#' && data[1] == '#')
2232
84.9k
                crc = seed;
2233
7.14M
            crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2234
7.14M
        }
2235
564k
    }
2236
564k
    return ~crc;
2237
564k
}
2238
2239
//-----------------------------------------------------------------------------
2240
// [SECTION] MISC HELPERS/UTILITIES (File functions)
2241
//-----------------------------------------------------------------------------
2242
2243
// Default file functions
2244
#ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2245
2246
ImFileHandle ImFileOpen(const char* filename, const char* mode)
2247
0
{
2248
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(__CYGWIN__) && !defined(__GNUC__)
2249
    // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames.
2250
    // Previously we used ImTextCountCharsFromUtf8/ImTextStrFromUtf8 here but we now need to support ImWchar16 and ImWchar32!
2251
    const int filename_wsize = ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0);
2252
    const int mode_wsize = ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, NULL, 0);
2253
2254
    // Use stack buffer if possible, otherwise heap buffer. Sizes include zero terminator.
2255
    // We don't rely on current ImGuiContext as this is implied to be a helper function which doesn't depend on it (see #7314).
2256
    wchar_t local_temp_stack[FILENAME_MAX];
2257
    ImVector<wchar_t> local_temp_heap;
2258
    if (filename_wsize + mode_wsize > IM_ARRAYSIZE(local_temp_stack))
2259
        local_temp_heap.resize(filename_wsize + mode_wsize);
2260
    wchar_t* filename_wbuf = local_temp_heap.Data ? local_temp_heap.Data : local_temp_stack;
2261
    wchar_t* mode_wbuf = filename_wbuf + filename_wsize;
2262
    ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, filename_wbuf, filename_wsize);
2263
    ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, mode_wbuf, mode_wsize);
2264
    return ::_wfopen(filename_wbuf, mode_wbuf);
2265
#else
2266
0
    return fopen(filename, mode);
2267
0
#endif
2268
0
}
2269
2270
// We should in theory be using fseeko()/ftello() with off_t and _fseeki64()/_ftelli64() with __int64, waiting for the PR that does that in a very portable pre-C++11 zero-warnings way.
2271
0
bool    ImFileClose(ImFileHandle f)     { return fclose(f) == 0; }
2272
0
ImU64   ImFileGetSize(ImFileHandle f)   { long off = 0, sz = 0; return ((off = ftell(f)) != -1 && !fseek(f, 0, SEEK_END) && (sz = ftell(f)) != -1 && !fseek(f, off, SEEK_SET)) ? (ImU64)sz : (ImU64)-1; }
2273
0
ImU64   ImFileRead(void* data, ImU64 sz, ImU64 count, ImFileHandle f)           { return fread(data, (size_t)sz, (size_t)count, f); }
2274
0
ImU64   ImFileWrite(const void* data, ImU64 sz, ImU64 count, ImFileHandle f)    { return fwrite(data, (size_t)sz, (size_t)count, f); }
2275
#endif // #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2276
2277
// Helper: Load file content into memory
2278
// Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree()
2279
// This can't really be used with "rt" because fseek size won't match read size.
2280
void*   ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size, int padding_bytes)
2281
0
{
2282
0
    IM_ASSERT(filename && mode);
2283
0
    if (out_file_size)
2284
0
        *out_file_size = 0;
2285
2286
0
    ImFileHandle f;
2287
0
    if ((f = ImFileOpen(filename, mode)) == NULL)
2288
0
        return NULL;
2289
2290
0
    size_t file_size = (size_t)ImFileGetSize(f);
2291
0
    if (file_size == (size_t)-1)
2292
0
    {
2293
0
        ImFileClose(f);
2294
0
        return NULL;
2295
0
    }
2296
2297
0
    void* file_data = IM_ALLOC(file_size + padding_bytes);
2298
0
    if (file_data == NULL)
2299
0
    {
2300
0
        ImFileClose(f);
2301
0
        return NULL;
2302
0
    }
2303
0
    if (ImFileRead(file_data, 1, file_size, f) != file_size)
2304
0
    {
2305
0
        ImFileClose(f);
2306
0
        IM_FREE(file_data);
2307
0
        return NULL;
2308
0
    }
2309
0
    if (padding_bytes > 0)
2310
0
        memset((void*)(((char*)file_data) + file_size), 0, (size_t)padding_bytes);
2311
2312
0
    ImFileClose(f);
2313
0
    if (out_file_size)
2314
0
        *out_file_size = file_size;
2315
2316
0
    return file_data;
2317
0
}
2318
2319
//-----------------------------------------------------------------------------
2320
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
2321
//-----------------------------------------------------------------------------
2322
2323
IM_MSVC_RUNTIME_CHECKS_OFF
2324
2325
// Convert UTF-8 to 32-bit character, process single character input.
2326
// A nearly-branchless UTF-8 decoder, based on work of Christopher Wellons (https://github.com/skeeto/branchless-utf8).
2327
// We handle UTF-8 decoding error by skipping forward.
2328
int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
2329
289k
{
2330
289k
    static const char lengths[32] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3, 4, 0 };
2331
289k
    static const int masks[]  = { 0x00, 0x7f, 0x1f, 0x0f, 0x07 };
2332
289k
    static const uint32_t mins[] = { 0x400000, 0, 0x80, 0x800, 0x10000 };
2333
289k
    static const int shiftc[] = { 0, 18, 12, 6, 0 };
2334
289k
    static const int shifte[] = { 0, 6, 4, 2, 0 };
2335
289k
    int len = lengths[*(const unsigned char*)in_text >> 3];
2336
289k
    int wanted = len + (len ? 0 : 1);
2337
2338
289k
    if (in_text_end == NULL)
2339
0
        in_text_end = in_text + wanted; // Max length, nulls will be taken into account.
2340
2341
    // Copy at most 'len' bytes, stop copying at 0 or past in_text_end. Branch predictor does a good job here,
2342
    // so it is fast even with excessive branching.
2343
289k
    unsigned char s[4];
2344
289k
    s[0] = in_text + 0 < in_text_end ? in_text[0] : 0;
2345
289k
    s[1] = in_text + 1 < in_text_end ? in_text[1] : 0;
2346
289k
    s[2] = in_text + 2 < in_text_end ? in_text[2] : 0;
2347
289k
    s[3] = in_text + 3 < in_text_end ? in_text[3] : 0;
2348
2349
    // Assume a four-byte character and load four bytes. Unused bits are shifted out.
2350
289k
    *out_char  = (uint32_t)(s[0] & masks[len]) << 18;
2351
289k
    *out_char |= (uint32_t)(s[1] & 0x3f) << 12;
2352
289k
    *out_char |= (uint32_t)(s[2] & 0x3f) <<  6;
2353
289k
    *out_char |= (uint32_t)(s[3] & 0x3f) <<  0;
2354
289k
    *out_char >>= shiftc[len];
2355
2356
    // Accumulate the various error conditions.
2357
289k
    int e = 0;
2358
289k
    e  = (*out_char < mins[len]) << 6; // non-canonical encoding
2359
289k
    e |= ((*out_char >> 11) == 0x1b) << 7;  // surrogate half?
2360
289k
    e |= (*out_char > IM_UNICODE_CODEPOINT_MAX) << 8;  // out of range?
2361
289k
    e |= (s[1] & 0xc0) >> 2;
2362
289k
    e |= (s[2] & 0xc0) >> 4;
2363
289k
    e |= (s[3]       ) >> 6;
2364
289k
    e ^= 0x2a; // top two bits of each tail byte correct?
2365
289k
    e >>= shifte[len];
2366
2367
289k
    if (e)
2368
10.9k
    {
2369
        // No bytes are consumed when *in_text == 0 || in_text == in_text_end.
2370
        // One byte is consumed in case of invalid first byte of in_text.
2371
        // All available bytes (at most `len` bytes) are consumed on incomplete/invalid second to last bytes.
2372
        // Invalid or incomplete input may consume less bytes than wanted, therefore every byte has to be inspected in s.
2373
10.9k
        wanted = ImMin(wanted, !!s[0] + !!s[1] + !!s[2] + !!s[3]);
2374
10.9k
        *out_char = IM_UNICODE_CODEPOINT_INVALID;
2375
10.9k
    }
2376
2377
289k
    return wanted;
2378
289k
}
2379
2380
int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
2381
0
{
2382
0
    ImWchar* buf_out = buf;
2383
0
    ImWchar* buf_end = buf + buf_size;
2384
0
    while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2385
0
    {
2386
0
        unsigned int c;
2387
0
        in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2388
0
        *buf_out++ = (ImWchar)c;
2389
0
    }
2390
0
    *buf_out = 0;
2391
0
    if (in_text_remaining)
2392
0
        *in_text_remaining = in_text;
2393
0
    return (int)(buf_out - buf);
2394
0
}
2395
2396
int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
2397
0
{
2398
0
    int char_count = 0;
2399
0
    while ((!in_text_end || in_text < in_text_end) && *in_text)
2400
0
    {
2401
0
        unsigned int c;
2402
0
        in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2403
0
        char_count++;
2404
0
    }
2405
0
    return char_count;
2406
0
}
2407
2408
// Based on stb_to_utf8() from github.com/nothings/stb/
2409
static inline int ImTextCharToUtf8_inline(char* buf, int buf_size, unsigned int c)
2410
0
{
2411
0
    if (c < 0x80)
2412
0
    {
2413
0
        buf[0] = (char)c;
2414
0
        return 1;
2415
0
    }
2416
0
    if (c < 0x800)
2417
0
    {
2418
0
        if (buf_size < 2) return 0;
2419
0
        buf[0] = (char)(0xc0 + (c >> 6));
2420
0
        buf[1] = (char)(0x80 + (c & 0x3f));
2421
0
        return 2;
2422
0
    }
2423
0
    if (c < 0x10000)
2424
0
    {
2425
0
        if (buf_size < 3) return 0;
2426
0
        buf[0] = (char)(0xe0 + (c >> 12));
2427
0
        buf[1] = (char)(0x80 + ((c >> 6) & 0x3f));
2428
0
        buf[2] = (char)(0x80 + ((c ) & 0x3f));
2429
0
        return 3;
2430
0
    }
2431
0
    if (c <= 0x10FFFF)
2432
0
    {
2433
0
        if (buf_size < 4) return 0;
2434
0
        buf[0] = (char)(0xf0 + (c >> 18));
2435
0
        buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));
2436
0
        buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));
2437
0
        buf[3] = (char)(0x80 + ((c ) & 0x3f));
2438
0
        return 4;
2439
0
    }
2440
    // Invalid code point, the max unicode is 0x10FFFF
2441
0
    return 0;
2442
0
}
2443
2444
const char* ImTextCharToUtf8(char out_buf[5], unsigned int c)
2445
0
{
2446
0
    int count = ImTextCharToUtf8_inline(out_buf, 5, c);
2447
0
    out_buf[count] = 0;
2448
0
    return out_buf;
2449
0
}
2450
2451
// Not optimal but we very rarely use this function.
2452
int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end)
2453
0
{
2454
0
    unsigned int unused = 0;
2455
0
    return ImTextCharFromUtf8(&unused, in_text, in_text_end);
2456
0
}
2457
2458
static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
2459
0
{
2460
0
    if (c < 0x80) return 1;
2461
0
    if (c < 0x800) return 2;
2462
0
    if (c < 0x10000) return 3;
2463
0
    if (c <= 0x10FFFF) return 4;
2464
0
    return 3;
2465
0
}
2466
2467
int ImTextStrToUtf8(char* out_buf, int out_buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
2468
0
{
2469
0
    char* buf_p = out_buf;
2470
0
    const char* buf_end = out_buf + out_buf_size;
2471
0
    while (buf_p < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2472
0
    {
2473
0
        unsigned int c = (unsigned int)(*in_text++);
2474
0
        if (c < 0x80)
2475
0
            *buf_p++ = (char)c;
2476
0
        else
2477
0
            buf_p += ImTextCharToUtf8_inline(buf_p, (int)(buf_end - buf_p - 1), c);
2478
0
    }
2479
0
    *buf_p = 0;
2480
0
    return (int)(buf_p - out_buf);
2481
0
}
2482
2483
int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
2484
0
{
2485
0
    int bytes_count = 0;
2486
0
    while ((!in_text_end || in_text < in_text_end) && *in_text)
2487
0
    {
2488
0
        unsigned int c = (unsigned int)(*in_text++);
2489
0
        if (c < 0x80)
2490
0
            bytes_count++;
2491
0
        else
2492
0
            bytes_count += ImTextCountUtf8BytesFromChar(c);
2493
0
    }
2494
0
    return bytes_count;
2495
0
}
2496
2497
const char* ImTextFindPreviousUtf8Codepoint(const char* in_text_start, const char* in_text_curr)
2498
0
{
2499
0
    while (in_text_curr > in_text_start)
2500
0
    {
2501
0
        in_text_curr--;
2502
0
        if ((*in_text_curr & 0xC0) != 0x80)
2503
0
            return in_text_curr;
2504
0
    }
2505
0
    return in_text_start;
2506
0
}
2507
2508
int ImTextCountLines(const char* in_text, const char* in_text_end)
2509
0
{
2510
0
    if (in_text_end == NULL)
2511
0
        in_text_end = in_text + strlen(in_text); // FIXME-OPT: Not optimal approach, discourage use for now.
2512
0
    int count = 0;
2513
0
    while (in_text < in_text_end)
2514
0
    {
2515
0
        const char* line_end = (const char*)memchr(in_text, '\n', in_text_end - in_text);
2516
0
        in_text = line_end ? line_end + 1 : in_text_end;
2517
0
        count++;
2518
0
    }
2519
0
    return count;
2520
0
}
2521
2522
IM_MSVC_RUNTIME_CHECKS_RESTORE
2523
2524
//-----------------------------------------------------------------------------
2525
// [SECTION] MISC HELPERS/UTILITIES (Color functions)
2526
// Note: The Convert functions are early design which are not consistent with other API.
2527
//-----------------------------------------------------------------------------
2528
2529
IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b)
2530
0
{
2531
0
    float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f;
2532
0
    int r = ImLerp((int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t);
2533
0
    int g = ImLerp((int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t);
2534
0
    int b = ImLerp((int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t);
2535
0
    return IM_COL32(r, g, b, 0xFF);
2536
0
}
2537
2538
ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
2539
263k
{
2540
263k
    float s = 1.0f / 255.0f;
2541
263k
    return ImVec4(
2542
263k
        ((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
2543
263k
        ((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
2544
263k
        ((in >> IM_COL32_B_SHIFT) & 0xFF) * s,
2545
263k
        ((in >> IM_COL32_A_SHIFT) & 0xFF) * s);
2546
263k
}
2547
2548
ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
2549
1.31M
{
2550
1.31M
    ImU32 out;
2551
1.31M
    out  = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;
2552
1.31M
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;
2553
1.31M
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;
2554
1.31M
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;
2555
1.31M
    return out;
2556
1.31M
}
2557
2558
// Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
2559
// Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
2560
void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
2561
0
{
2562
0
    float K = 0.f;
2563
0
    if (g < b)
2564
0
    {
2565
0
        ImSwap(g, b);
2566
0
        K = -1.f;
2567
0
    }
2568
0
    if (r < g)
2569
0
    {
2570
0
        ImSwap(r, g);
2571
0
        K = -2.f / 6.f - K;
2572
0
    }
2573
2574
0
    const float chroma = r - (g < b ? g : b);
2575
0
    out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f));
2576
0
    out_s = chroma / (r + 1e-20f);
2577
0
    out_v = r;
2578
0
}
2579
2580
// Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
2581
// also http://en.wikipedia.org/wiki/HSL_and_HSV
2582
void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
2583
0
{
2584
0
    if (s == 0.0f)
2585
0
    {
2586
        // gray
2587
0
        out_r = out_g = out_b = v;
2588
0
        return;
2589
0
    }
2590
2591
0
    h = ImFmod(h, 1.0f) / (60.0f / 360.0f);
2592
0
    int   i = (int)h;
2593
0
    float f = h - (float)i;
2594
0
    float p = v * (1.0f - s);
2595
0
    float q = v * (1.0f - s * f);
2596
0
    float t = v * (1.0f - s * (1.0f - f));
2597
2598
0
    switch (i)
2599
0
    {
2600
0
    case 0: out_r = v; out_g = t; out_b = p; break;
2601
0
    case 1: out_r = q; out_g = v; out_b = p; break;
2602
0
    case 2: out_r = p; out_g = v; out_b = t; break;
2603
0
    case 3: out_r = p; out_g = q; out_b = v; break;
2604
0
    case 4: out_r = t; out_g = p; out_b = v; break;
2605
0
    case 5: default: out_r = v; out_g = p; out_b = q; break;
2606
0
    }
2607
0
}
2608
2609
//-----------------------------------------------------------------------------
2610
// [SECTION] ImGuiStorage
2611
// Helper: Key->value storage
2612
//-----------------------------------------------------------------------------
2613
2614
// std::lower_bound but without the bullshit
2615
ImGuiStoragePair* ImLowerBound(ImGuiStoragePair* in_begin, ImGuiStoragePair* in_end, ImGuiID key)
2616
193k
{
2617
193k
    ImGuiStoragePair* in_p = in_begin;
2618
580k
    for (size_t count = (size_t)(in_end - in_p); count > 0; )
2619
387k
    {
2620
387k
        size_t count2 = count >> 1;
2621
387k
        ImGuiStoragePair* mid = in_p + count2;
2622
387k
        if (mid->key < key)
2623
108k
        {
2624
108k
            in_p = ++mid;
2625
108k
            count -= count2 + 1;
2626
108k
        }
2627
278k
        else
2628
278k
        {
2629
278k
            count = count2;
2630
278k
        }
2631
387k
    }
2632
193k
    return in_p;
2633
193k
}
2634
2635
IM_MSVC_RUNTIME_CHECKS_OFF
2636
static int IMGUI_CDECL PairComparerByID(const void* lhs, const void* rhs)
2637
0
{
2638
    // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.
2639
0
    ImGuiID lhs_v = ((const ImGuiStoragePair*)lhs)->key;
2640
0
    ImGuiID rhs_v = ((const ImGuiStoragePair*)rhs)->key;
2641
0
    return (lhs_v > rhs_v ? +1 : lhs_v < rhs_v ? -1 : 0);
2642
0
}
2643
2644
// For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
2645
void ImGuiStorage::BuildSortByKey()
2646
0
{
2647
0
    ImQsort(Data.Data, (size_t)Data.Size, sizeof(ImGuiStoragePair), PairComparerByID);
2648
0
}
2649
2650
int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
2651
0
{
2652
0
    ImGuiStoragePair* it = ImLowerBound(const_cast<ImGuiStoragePair*>(Data.Data), const_cast<ImGuiStoragePair*>(Data.Data + Data.Size), key);
2653
0
    if (it == Data.Data + Data.Size || it->key != key)
2654
0
        return default_val;
2655
0
    return it->val_i;
2656
0
}
2657
2658
bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
2659
0
{
2660
0
    return GetInt(key, default_val ? 1 : 0) != 0;
2661
0
}
2662
2663
float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
2664
0
{
2665
0
    ImGuiStoragePair* it = ImLowerBound(const_cast<ImGuiStoragePair*>(Data.Data), const_cast<ImGuiStoragePair*>(Data.Data + Data.Size), key);
2666
0
    if (it == Data.Data + Data.Size || it->key != key)
2667
0
        return default_val;
2668
0
    return it->val_f;
2669
0
}
2670
2671
void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
2672
193k
{
2673
193k
    ImGuiStoragePair* it = ImLowerBound(const_cast<ImGuiStoragePair*>(Data.Data), const_cast<ImGuiStoragePair*>(Data.Data + Data.Size), key);
2674
193k
    if (it == Data.Data + Data.Size || it->key != key)
2675
3
        return NULL;
2676
193k
    return it->val_p;
2677
193k
}
2678
2679
// References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer.
2680
int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
2681
0
{
2682
0
    ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
2683
0
    if (it == Data.Data + Data.Size || it->key != key)
2684
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2685
0
    return &it->val_i;
2686
0
}
2687
2688
bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
2689
0
{
2690
0
    return (bool*)GetIntRef(key, default_val ? 1 : 0);
2691
0
}
2692
2693
float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
2694
0
{
2695
0
    ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
2696
0
    if (it == Data.Data + Data.Size || it->key != key)
2697
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2698
0
    return &it->val_f;
2699
0
}
2700
2701
void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
2702
0
{
2703
0
    ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
2704
0
    if (it == Data.Data + Data.Size || it->key != key)
2705
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2706
0
    return &it->val_p;
2707
0
}
2708
2709
// FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame)
2710
void ImGuiStorage::SetInt(ImGuiID key, int val)
2711
0
{
2712
0
    ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
2713
0
    if (it == Data.Data + Data.Size || it->key != key)
2714
0
        Data.insert(it, ImGuiStoragePair(key, val));
2715
0
    else
2716
0
        it->val_i = val;
2717
0
}
2718
2719
void ImGuiStorage::SetBool(ImGuiID key, bool val)
2720
0
{
2721
0
    SetInt(key, val ? 1 : 0);
2722
0
}
2723
2724
void ImGuiStorage::SetFloat(ImGuiID key, float val)
2725
0
{
2726
0
    ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
2727
0
    if (it == Data.Data + Data.Size || it->key != key)
2728
0
        Data.insert(it, ImGuiStoragePair(key, val));
2729
0
    else
2730
0
        it->val_f = val;
2731
0
}
2732
2733
void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
2734
3
{
2735
3
    ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
2736
3
    if (it == Data.Data + Data.Size || it->key != key)
2737
3
        Data.insert(it, ImGuiStoragePair(key, val));
2738
0
    else
2739
0
        it->val_p = val;
2740
3
}
2741
2742
void ImGuiStorage::SetAllInt(int v)
2743
0
{
2744
0
    for (int i = 0; i < Data.Size; i++)
2745
0
        Data[i].val_i = v;
2746
0
}
2747
IM_MSVC_RUNTIME_CHECKS_RESTORE
2748
2749
//-----------------------------------------------------------------------------
2750
// [SECTION] ImGuiTextFilter
2751
//-----------------------------------------------------------------------------
2752
2753
// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
2754
ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) //-V1077
2755
0
{
2756
0
    InputBuf[0] = 0;
2757
0
    CountGrep = 0;
2758
0
    if (default_filter)
2759
0
    {
2760
0
        ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf));
2761
0
        Build();
2762
0
    }
2763
0
}
2764
2765
bool ImGuiTextFilter::Draw(const char* label, float width)
2766
0
{
2767
0
    if (width != 0.0f)
2768
0
        ImGui::SetNextItemWidth(width);
2769
0
    bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf));
2770
0
    if (value_changed)
2771
0
        Build();
2772
0
    return value_changed;
2773
0
}
2774
2775
void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector<ImGuiTextRange>* out) const
2776
0
{
2777
0
    out->resize(0);
2778
0
    const char* wb = b;
2779
0
    const char* we = wb;
2780
0
    while (we < e)
2781
0
    {
2782
0
        if (*we == separator)
2783
0
        {
2784
0
            out->push_back(ImGuiTextRange(wb, we));
2785
0
            wb = we + 1;
2786
0
        }
2787
0
        we++;
2788
0
    }
2789
0
    if (wb != we)
2790
0
        out->push_back(ImGuiTextRange(wb, we));
2791
0
}
2792
2793
void ImGuiTextFilter::Build()
2794
0
{
2795
0
    Filters.resize(0);
2796
0
    ImGuiTextRange input_range(InputBuf, InputBuf + strlen(InputBuf));
2797
0
    input_range.split(',', &Filters);
2798
2799
0
    CountGrep = 0;
2800
0
    for (ImGuiTextRange& f : Filters)
2801
0
    {
2802
0
        while (f.b < f.e && ImCharIsBlankA(f.b[0]))
2803
0
            f.b++;
2804
0
        while (f.e > f.b && ImCharIsBlankA(f.e[-1]))
2805
0
            f.e--;
2806
0
        if (f.empty())
2807
0
            continue;
2808
0
        if (f.b[0] != '-')
2809
0
            CountGrep += 1;
2810
0
    }
2811
0
}
2812
2813
bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
2814
0
{
2815
0
    if (Filters.Size == 0)
2816
0
        return true;
2817
2818
0
    if (text == NULL)
2819
0
        text = text_end = "";
2820
2821
0
    for (const ImGuiTextRange& f : Filters)
2822
0
    {
2823
0
        if (f.b == f.e)
2824
0
            continue;
2825
0
        if (f.b[0] == '-')
2826
0
        {
2827
            // Subtract
2828
0
            if (ImStristr(text, text_end, f.b + 1, f.e) != NULL)
2829
0
                return false;
2830
0
        }
2831
0
        else
2832
0
        {
2833
            // Grep
2834
0
            if (ImStristr(text, text_end, f.b, f.e) != NULL)
2835
0
                return true;
2836
0
        }
2837
0
    }
2838
2839
    // Implicit * grep
2840
0
    if (CountGrep == 0)
2841
0
        return true;
2842
2843
0
    return false;
2844
0
}
2845
2846
//-----------------------------------------------------------------------------
2847
// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
2848
//-----------------------------------------------------------------------------
2849
2850
// On some platform vsnprintf() takes va_list by reference and modifies it.
2851
// va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
2852
#ifndef va_copy
2853
#if defined(__GNUC__) || defined(__clang__)
2854
#define va_copy(dest, src) __builtin_va_copy(dest, src)
2855
#else
2856
#define va_copy(dest, src) (dest = src)
2857
#endif
2858
#endif
2859
2860
char ImGuiTextBuffer::EmptyString[1] = { 0 };
2861
2862
void ImGuiTextBuffer::append(const char* str, const char* str_end)
2863
0
{
2864
0
    int len = str_end ? (int)(str_end - str) : (int)strlen(str);
2865
2866
    // Add zero-terminator the first time
2867
0
    const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2868
0
    const int needed_sz = write_off + len;
2869
0
    if (write_off + len >= Buf.Capacity)
2870
0
    {
2871
0
        int new_capacity = Buf.Capacity * 2;
2872
0
        Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
2873
0
    }
2874
2875
0
    Buf.resize(needed_sz);
2876
0
    memcpy(&Buf[write_off - 1], str, (size_t)len);
2877
0
    Buf[write_off - 1 + len] = 0;
2878
0
}
2879
2880
void ImGuiTextBuffer::appendf(const char* fmt, ...)
2881
0
{
2882
0
    va_list args;
2883
0
    va_start(args, fmt);
2884
0
    appendfv(fmt, args);
2885
0
    va_end(args);
2886
0
}
2887
2888
// Helper: Text buffer for logging/accumulating text
2889
void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
2890
0
{
2891
0
    va_list args_copy;
2892
0
    va_copy(args_copy, args);
2893
2894
0
    int len = ImFormatStringV(NULL, 0, fmt, args);         // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
2895
0
    if (len <= 0)
2896
0
    {
2897
0
        va_end(args_copy);
2898
0
        return;
2899
0
    }
2900
2901
    // Add zero-terminator the first time
2902
0
    const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2903
0
    const int needed_sz = write_off + len;
2904
0
    if (write_off + len >= Buf.Capacity)
2905
0
    {
2906
0
        int new_capacity = Buf.Capacity * 2;
2907
0
        Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
2908
0
    }
2909
2910
0
    Buf.resize(needed_sz);
2911
0
    ImFormatStringV(&Buf[write_off - 1], (size_t)len + 1, fmt, args_copy);
2912
0
    va_end(args_copy);
2913
0
}
2914
2915
void ImGuiTextIndex::append(const char* base, int old_size, int new_size)
2916
0
{
2917
0
    IM_ASSERT(old_size >= 0 && new_size >= old_size && new_size >= EndOffset);
2918
0
    if (old_size == new_size)
2919
0
        return;
2920
0
    if (EndOffset == 0 || base[EndOffset - 1] == '\n')
2921
0
        LineOffsets.push_back(EndOffset);
2922
0
    const char* base_end = base + new_size;
2923
0
    for (const char* p = base + old_size; (p = (const char*)memchr(p, '\n', base_end - p)) != 0; )
2924
0
        if (++p < base_end) // Don't push a trailing offset on last \n
2925
0
            LineOffsets.push_back((int)(intptr_t)(p - base));
2926
0
    EndOffset = ImMax(EndOffset, new_size);
2927
0
}
2928
2929
//-----------------------------------------------------------------------------
2930
// [SECTION] ImGuiListClipper
2931
//-----------------------------------------------------------------------------
2932
2933
// FIXME-TABLE: This prevents us from using ImGuiListClipper _inside_ a table cell.
2934
// The problem we have is that without a Begin/End scheme for rows using the clipper is ambiguous.
2935
static bool GetSkipItemForListClipping()
2936
0
{
2937
0
    ImGuiContext& g = *GImGui;
2938
0
    return (g.CurrentTable ? g.CurrentTable->HostSkipItems : g.CurrentWindow->SkipItems);
2939
0
}
2940
2941
static void ImGuiListClipper_SortAndFuseRanges(ImVector<ImGuiListClipperRange>& ranges, int offset = 0)
2942
0
{
2943
0
    if (ranges.Size - offset <= 1)
2944
0
        return;
2945
2946
    // Helper to order ranges and fuse them together if possible (bubble sort is fine as we are only sorting 2-3 entries)
2947
0
    for (int sort_end = ranges.Size - offset - 1; sort_end > 0; --sort_end)
2948
0
        for (int i = offset; i < sort_end + offset; ++i)
2949
0
            if (ranges[i].Min > ranges[i + 1].Min)
2950
0
                ImSwap(ranges[i], ranges[i + 1]);
2951
2952
    // Now fuse ranges together as much as possible.
2953
0
    for (int i = 1 + offset; i < ranges.Size; i++)
2954
0
    {
2955
0
        IM_ASSERT(!ranges[i].PosToIndexConvert && !ranges[i - 1].PosToIndexConvert);
2956
0
        if (ranges[i - 1].Max < ranges[i].Min)
2957
0
            continue;
2958
0
        ranges[i - 1].Min = ImMin(ranges[i - 1].Min, ranges[i].Min);
2959
0
        ranges[i - 1].Max = ImMax(ranges[i - 1].Max, ranges[i].Max);
2960
0
        ranges.erase(ranges.Data + i);
2961
0
        i--;
2962
0
    }
2963
0
}
2964
2965
static void ImGuiListClipper_SeekCursorAndSetupPrevLine(float pos_y, float line_height)
2966
0
{
2967
    // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor.
2968
    // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.
2969
    // The clipper should probably have a final step to display the last item in a regular manner, maybe with an opt-out flag for data sets which may have costly seek?
2970
0
    ImGuiContext& g = *GImGui;
2971
0
    ImGuiWindow* window = g.CurrentWindow;
2972
0
    float off_y = pos_y - window->DC.CursorPos.y;
2973
0
    window->DC.CursorPos.y = pos_y;
2974
0
    window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, pos_y - g.Style.ItemSpacing.y);
2975
0
    window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height;  // Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage.
2976
0
    window->DC.PrevLineSize.y = (line_height - g.Style.ItemSpacing.y);      // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list.
2977
0
    if (ImGuiOldColumns* columns = window->DC.CurrentColumns)
2978
0
        columns->LineMinY = window->DC.CursorPos.y;                         // Setting this so that cell Y position are set properly
2979
0
    if (ImGuiTable* table = g.CurrentTable)
2980
0
    {
2981
0
        if (table->IsInsideRow)
2982
0
            ImGui::TableEndRow(table);
2983
0
        table->RowPosY2 = window->DC.CursorPos.y;
2984
0
        const int row_increase = (int)((off_y / line_height) + 0.5f);
2985
        //table->CurrentRow += row_increase; // Can't do without fixing TableEndRow()
2986
0
        table->RowBgColorCounter += row_increase;
2987
0
    }
2988
0
}
2989
2990
ImGuiListClipper::ImGuiListClipper()
2991
0
{
2992
0
    memset(this, 0, sizeof(*this));
2993
0
}
2994
2995
ImGuiListClipper::~ImGuiListClipper()
2996
0
{
2997
0
    End();
2998
0
}
2999
3000
void ImGuiListClipper::Begin(int items_count, float items_height)
3001
0
{
3002
0
    if (Ctx == NULL)
3003
0
        Ctx = ImGui::GetCurrentContext();
3004
3005
0
    ImGuiContext& g = *Ctx;
3006
0
    ImGuiWindow* window = g.CurrentWindow;
3007
0
    IMGUI_DEBUG_LOG_CLIPPER("Clipper: Begin(%d,%.2f) in '%s'\n", items_count, items_height, window->Name);
3008
3009
0
    if (ImGuiTable* table = g.CurrentTable)
3010
0
        if (table->IsInsideRow)
3011
0
            ImGui::TableEndRow(table);
3012
3013
0
    StartPosY = window->DC.CursorPos.y;
3014
0
    ItemsHeight = items_height;
3015
0
    ItemsCount = items_count;
3016
0
    DisplayStart = -1;
3017
0
    DisplayEnd = 0;
3018
3019
    // Acquire temporary buffer
3020
0
    if (++g.ClipperTempDataStacked > g.ClipperTempData.Size)
3021
0
        g.ClipperTempData.resize(g.ClipperTempDataStacked, ImGuiListClipperData());
3022
0
    ImGuiListClipperData* data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
3023
0
    data->Reset(this);
3024
0
    data->LossynessOffset = window->DC.CursorStartPosLossyness.y;
3025
0
    TempData = data;
3026
0
    StartSeekOffsetY = data->LossynessOffset;
3027
0
}
3028
3029
void ImGuiListClipper::End()
3030
0
{
3031
0
    if (ImGuiListClipperData* data = (ImGuiListClipperData*)TempData)
3032
0
    {
3033
        // In theory here we should assert that we are already at the right position, but it seems saner to just seek at the end and not assert/crash the user.
3034
0
        ImGuiContext& g = *Ctx;
3035
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: End() in '%s'\n", g.CurrentWindow->Name);
3036
0
        if (ItemsCount >= 0 && ItemsCount < INT_MAX && DisplayStart >= 0)
3037
0
            SeekCursorForItem(ItemsCount);
3038
3039
        // Restore temporary buffer and fix back pointers which may be invalidated when nesting
3040
0
        IM_ASSERT(data->ListClipper == this);
3041
0
        data->StepNo = data->Ranges.Size;
3042
0
        if (--g.ClipperTempDataStacked > 0)
3043
0
        {
3044
0
            data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
3045
0
            data->ListClipper->TempData = data;
3046
0
        }
3047
0
        TempData = NULL;
3048
0
    }
3049
0
    ItemsCount = -1;
3050
0
}
3051
3052
void ImGuiListClipper::IncludeItemsByIndex(int item_begin, int item_end)
3053
0
{
3054
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)TempData;
3055
0
    IM_ASSERT(DisplayStart < 0); // Only allowed after Begin() and if there has not been a specified range yet.
3056
0
    IM_ASSERT(item_begin <= item_end);
3057
0
    if (item_begin < item_end)
3058
0
        data->Ranges.push_back(ImGuiListClipperRange::FromIndices(item_begin, item_end));
3059
0
}
3060
3061
// This is already called while stepping.
3062
// The ONLY reason you may want to call this is if you passed INT_MAX to ImGuiListClipper::Begin() because you couldn't step item count beforehand.
3063
void ImGuiListClipper::SeekCursorForItem(int item_n)
3064
0
{
3065
    // - Perform the add and multiply with double to allow seeking through larger ranges.
3066
    // - StartPosY starts from ItemsFrozen, by adding SeekOffsetY we generally cancel that out (SeekOffsetY == LossynessOffset - ItemsFrozen * ItemsHeight).
3067
    // - The reason we store SeekOffsetY instead of inferring it, is because we want to allow user to perform Seek after the last step, where ImGuiListClipperData is already done.
3068
0
    float pos_y = (float)((double)StartPosY + StartSeekOffsetY + (double)item_n * ItemsHeight);
3069
0
    ImGuiListClipper_SeekCursorAndSetupPrevLine(pos_y, ItemsHeight);
3070
0
}
3071
3072
static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper)
3073
0
{
3074
0
    ImGuiContext& g = *clipper->Ctx;
3075
0
    ImGuiWindow* window = g.CurrentWindow;
3076
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
3077
0
    IM_ASSERT(data != NULL && "Called ImGuiListClipper::Step() too many times, or before ImGuiListClipper::Begin() ?");
3078
3079
0
    ImGuiTable* table = g.CurrentTable;
3080
0
    if (table && table->IsInsideRow)
3081
0
        ImGui::TableEndRow(table);
3082
3083
    // No items
3084
0
    if (clipper->ItemsCount == 0 || GetSkipItemForListClipping())
3085
0
        return false;
3086
3087
    // While we are in frozen row state, keep displaying items one by one, unclipped
3088
    // FIXME: Could be stored as a table-agnostic state.
3089
0
    if (data->StepNo == 0 && table != NULL && !table->IsUnfrozenRows)
3090
0
    {
3091
0
        clipper->DisplayStart = data->ItemsFrozen;
3092
0
        clipper->DisplayEnd = ImMin(data->ItemsFrozen + 1, clipper->ItemsCount);
3093
0
        if (clipper->DisplayStart < clipper->DisplayEnd)
3094
0
            data->ItemsFrozen++;
3095
0
        return true;
3096
0
    }
3097
3098
    // Step 0: Let you process the first element (regardless of it being visible or not, so we can measure the element height)
3099
0
    bool calc_clipping = false;
3100
0
    if (data->StepNo == 0)
3101
0
    {
3102
0
        clipper->StartPosY = window->DC.CursorPos.y;
3103
0
        if (clipper->ItemsHeight <= 0.0f)
3104
0
        {
3105
            // Submit the first item (or range) so we can measure its height (generally the first range is 0..1)
3106
0
            data->Ranges.push_front(ImGuiListClipperRange::FromIndices(data->ItemsFrozen, data->ItemsFrozen + 1));
3107
0
            clipper->DisplayStart = ImMax(data->Ranges[0].Min, data->ItemsFrozen);
3108
0
            clipper->DisplayEnd = ImMin(data->Ranges[0].Max, clipper->ItemsCount);
3109
0
            data->StepNo = 1;
3110
0
            return true;
3111
0
        }
3112
0
        calc_clipping = true;   // If on the first step with known item height, calculate clipping.
3113
0
    }
3114
3115
    // Step 1: Let the clipper infer height from first range
3116
0
    if (clipper->ItemsHeight <= 0.0f)
3117
0
    {
3118
0
        IM_ASSERT(data->StepNo == 1);
3119
0
        if (table)
3120
0
            IM_ASSERT(table->RowPosY1 == clipper->StartPosY && table->RowPosY2 == window->DC.CursorPos.y);
3121
3122
0
        clipper->ItemsHeight = (window->DC.CursorPos.y - clipper->StartPosY) / (float)(clipper->DisplayEnd - clipper->DisplayStart);
3123
0
        bool affected_by_floating_point_precision = ImIsFloatAboveGuaranteedIntegerPrecision(clipper->StartPosY) || ImIsFloatAboveGuaranteedIntegerPrecision(window->DC.CursorPos.y);
3124
0
        if (affected_by_floating_point_precision)
3125
0
            clipper->ItemsHeight = window->DC.PrevLineSize.y + g.Style.ItemSpacing.y; // FIXME: Technically wouldn't allow multi-line entries.
3126
0
        if (clipper->ItemsHeight == 0.0f && clipper->ItemsCount == INT_MAX) // Accept that no item have been submitted if in indeterminate mode.
3127
0
            return false;
3128
0
        IM_ASSERT(clipper->ItemsHeight > 0.0f && "Unable to calculate item height! First item hasn't moved the cursor vertically!");
3129
0
        calc_clipping = true;   // If item height had to be calculated, calculate clipping afterwards.
3130
0
    }
3131
3132
    // Step 0 or 1: Calculate the actual ranges of visible elements.
3133
0
    const int already_submitted = clipper->DisplayEnd;
3134
0
    if (calc_clipping)
3135
0
    {
3136
        // Record seek offset, this is so ImGuiListClipper::Seek() can be called after ImGuiListClipperData is done
3137
0
        clipper->StartSeekOffsetY = (double)data->LossynessOffset - data->ItemsFrozen * (double)clipper->ItemsHeight;
3138
3139
0
        if (g.LogEnabled)
3140
0
        {
3141
            // If logging is active, do not perform any clipping
3142
0
            data->Ranges.push_back(ImGuiListClipperRange::FromIndices(0, clipper->ItemsCount));
3143
0
        }
3144
0
        else
3145
0
        {
3146
            // Add range selected to be included for navigation
3147
0
            const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
3148
0
            if (is_nav_request)
3149
0
                data->Ranges.push_back(ImGuiListClipperRange::FromPositions(g.NavScoringNoClipRect.Min.y, g.NavScoringNoClipRect.Max.y, 0, 0));
3150
0
            if (is_nav_request && (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && g.NavTabbingDir == -1)
3151
0
                data->Ranges.push_back(ImGuiListClipperRange::FromIndices(clipper->ItemsCount - 1, clipper->ItemsCount));
3152
3153
            // Add focused/active item
3154
0
            ImRect nav_rect_abs = ImGui::WindowRectRelToAbs(window, window->NavRectRel[0]);
3155
0
            if (g.NavId != 0 && window->NavLastIds[0] == g.NavId)
3156
0
                data->Ranges.push_back(ImGuiListClipperRange::FromPositions(nav_rect_abs.Min.y, nav_rect_abs.Max.y, 0, 0));
3157
3158
            // Add visible range
3159
0
            float min_y = window->ClipRect.Min.y;
3160
0
            float max_y = window->ClipRect.Max.y;
3161
3162
            // Add box selection range
3163
0
            ImGuiBoxSelectState* bs = &g.BoxSelectState;
3164
0
            if (bs->IsActive && bs->Window == window)
3165
0
            {
3166
                // FIXME: Selectable() use of half-ItemSpacing isn't consistent in matter of layout, as ItemAdd(bb) stray above ItemSize()'s CursorPos.
3167
                // RangeSelect's BoxSelect relies on comparing overlap of previous and current rectangle and is sensitive to that.
3168
                // As a workaround we currently half ItemSpacing worth on each side.
3169
0
                min_y -= g.Style.ItemSpacing.y;
3170
0
                max_y += g.Style.ItemSpacing.y;
3171
3172
                // Box-select on 2D area requires different clipping.
3173
0
                if (bs->UnclipMode)
3174
0
                    data->Ranges.push_back(ImGuiListClipperRange::FromPositions(bs->UnclipRect.Min.y, bs->UnclipRect.Max.y, 0, 0));
3175
0
            }
3176
3177
0
            const int off_min = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up) ? -1 : 0;
3178
0
            const int off_max = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down) ? 1 : 0;
3179
0
            data->Ranges.push_back(ImGuiListClipperRange::FromPositions(min_y, max_y, off_min, off_max));
3180
0
        }
3181
3182
        // Convert position ranges to item index ranges
3183
        // - Very important: when a starting position is after our maximum item, we set Min to (ItemsCount - 1). This allows us to handle most forms of wrapping.
3184
        // - Due to how Selectable extra padding they tend to be "unaligned" with exact unit in the item list,
3185
        //   which with the flooring/ceiling tend to lead to 2 items instead of one being submitted.
3186
0
        for (ImGuiListClipperRange& range : data->Ranges)
3187
0
            if (range.PosToIndexConvert)
3188
0
            {
3189
0
                int m1 = (int)(((double)range.Min - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight);
3190
0
                int m2 = (int)((((double)range.Max - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight) + 0.999999f);
3191
0
                range.Min = ImClamp(already_submitted + m1 + range.PosToIndexOffsetMin, already_submitted, clipper->ItemsCount - 1);
3192
0
                range.Max = ImClamp(already_submitted + m2 + range.PosToIndexOffsetMax, range.Min + 1, clipper->ItemsCount);
3193
0
                range.PosToIndexConvert = false;
3194
0
            }
3195
0
        ImGuiListClipper_SortAndFuseRanges(data->Ranges, data->StepNo);
3196
0
    }
3197
3198
    // Step 0+ (if item height is given in advance) or 1+: Display the next range in line.
3199
0
    while (data->StepNo < data->Ranges.Size)
3200
0
    {
3201
0
        clipper->DisplayStart = ImMax(data->Ranges[data->StepNo].Min, already_submitted);
3202
0
        clipper->DisplayEnd = ImMin(data->Ranges[data->StepNo].Max, clipper->ItemsCount);
3203
0
        if (clipper->DisplayStart > already_submitted) //-V1051
3204
0
            clipper->SeekCursorForItem(clipper->DisplayStart);
3205
0
        data->StepNo++;
3206
0
        if (clipper->DisplayStart == clipper->DisplayEnd && data->StepNo < data->Ranges.Size)
3207
0
            continue;
3208
0
        return true;
3209
0
    }
3210
3211
    // After the last step: Let the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd),
3212
    // Advance the cursor to the end of the list and then returns 'false' to end the loop.
3213
0
    if (clipper->ItemsCount < INT_MAX)
3214
0
        clipper->SeekCursorForItem(clipper->ItemsCount);
3215
3216
0
    return false;
3217
0
}
3218
3219
bool ImGuiListClipper::Step()
3220
0
{
3221
0
    ImGuiContext& g = *Ctx;
3222
0
    bool need_items_height = (ItemsHeight <= 0.0f);
3223
0
    bool ret = ImGuiListClipper_StepInternal(this);
3224
0
    if (ret && (DisplayStart == DisplayEnd))
3225
0
        ret = false;
3226
0
    if (g.CurrentTable && g.CurrentTable->IsUnfrozenRows == false)
3227
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): inside frozen table row.\n");
3228
0
    if (need_items_height && ItemsHeight > 0.0f)
3229
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): computed ItemsHeight: %.2f.\n", ItemsHeight);
3230
0
    if (ret)
3231
0
    {
3232
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): display %d to %d.\n", DisplayStart, DisplayEnd);
3233
0
    }
3234
0
    else
3235
0
    {
3236
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): End.\n");
3237
0
        End();
3238
0
    }
3239
0
    return ret;
3240
0
}
3241
3242
//-----------------------------------------------------------------------------
3243
// [SECTION] STYLING
3244
//-----------------------------------------------------------------------------
3245
3246
ImGuiStyle& ImGui::GetStyle()
3247
178k
{
3248
178k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
3249
178k
    return GImGui->Style;
3250
178k
}
3251
3252
ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
3253
1.13M
{
3254
1.13M
    ImGuiStyle& style = GImGui->Style;
3255
1.13M
    ImVec4 c = style.Colors[idx];
3256
1.13M
    c.w *= style.Alpha * alpha_mul;
3257
1.13M
    return ColorConvertFloat4ToU32(c);
3258
1.13M
}
3259
3260
ImU32 ImGui::GetColorU32(const ImVec4& col)
3261
0
{
3262
0
    ImGuiStyle& style = GImGui->Style;
3263
0
    ImVec4 c = col;
3264
0
    c.w *= style.Alpha;
3265
0
    return ColorConvertFloat4ToU32(c);
3266
0
}
3267
3268
const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
3269
0
{
3270
0
    ImGuiStyle& style = GImGui->Style;
3271
0
    return style.Colors[idx];
3272
0
}
3273
3274
ImU32 ImGui::GetColorU32(ImU32 col, float alpha_mul)
3275
0
{
3276
0
    ImGuiStyle& style = GImGui->Style;
3277
0
    alpha_mul *= style.Alpha;
3278
0
    if (alpha_mul >= 1.0f)
3279
0
        return col;
3280
0
    ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
3281
0
    a = (ImU32)(a * alpha_mul); // We don't need to clamp 0..255 because alpha is in 0..1 range.
3282
0
    return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
3283
0
}
3284
3285
// FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store the in-flight colors as ImU32
3286
void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
3287
0
{
3288
0
    ImGuiContext& g = *GImGui;
3289
0
    ImGuiColorMod backup;
3290
0
    backup.Col = idx;
3291
0
    backup.BackupValue = g.Style.Colors[idx];
3292
0
    g.ColorStack.push_back(backup);
3293
0
    if (g.DebugFlashStyleColorIdx != idx)
3294
0
        g.Style.Colors[idx] = ColorConvertU32ToFloat4(col);
3295
0
}
3296
3297
void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
3298
84.9k
{
3299
84.9k
    ImGuiContext& g = *GImGui;
3300
84.9k
    ImGuiColorMod backup;
3301
84.9k
    backup.Col = idx;
3302
84.9k
    backup.BackupValue = g.Style.Colors[idx];
3303
84.9k
    g.ColorStack.push_back(backup);
3304
84.9k
    if (g.DebugFlashStyleColorIdx != idx)
3305
84.9k
        g.Style.Colors[idx] = col;
3306
84.9k
}
3307
3308
void ImGui::PopStyleColor(int count)
3309
84.9k
{
3310
84.9k
    ImGuiContext& g = *GImGui;
3311
84.9k
    if (g.ColorStack.Size < count)
3312
0
    {
3313
0
        IM_ASSERT_USER_ERROR(g.ColorStack.Size > count, "Calling PopStyleColor() too many times!");
3314
0
        count = g.ColorStack.Size;
3315
0
    }
3316
169k
    while (count > 0)
3317
84.9k
    {
3318
84.9k
        ImGuiColorMod& backup = g.ColorStack.back();
3319
84.9k
        g.Style.Colors[backup.Col] = backup.BackupValue;
3320
84.9k
        g.ColorStack.pop_back();
3321
84.9k
        count--;
3322
84.9k
    }
3323
84.9k
}
3324
3325
static const ImGuiCol GWindowDockStyleColors[ImGuiWindowDockStyleCol_COUNT] =
3326
{
3327
    ImGuiCol_Text, ImGuiCol_TabHovered, ImGuiCol_Tab, ImGuiCol_TabSelected, ImGuiCol_TabSelectedOverline, ImGuiCol_TabDimmed, ImGuiCol_TabDimmedSelected, ImGuiCol_TabDimmedSelectedOverline,
3328
};
3329
3330
static const ImGuiDataVarInfo GStyleVarInfo[] =
3331
{
3332
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, Alpha) },                     // ImGuiStyleVar_Alpha
3333
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, DisabledAlpha) },             // ImGuiStyleVar_DisabledAlpha
3334
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, WindowPadding) },             // ImGuiStyleVar_WindowPadding
3335
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, WindowRounding) },            // ImGuiStyleVar_WindowRounding
3336
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, WindowBorderSize) },          // ImGuiStyleVar_WindowBorderSize
3337
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, WindowMinSize) },             // ImGuiStyleVar_WindowMinSize
3338
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, WindowTitleAlign) },          // ImGuiStyleVar_WindowTitleAlign
3339
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ChildRounding) },             // ImGuiStyleVar_ChildRounding
3340
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ChildBorderSize) },           // ImGuiStyleVar_ChildBorderSize
3341
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, PopupRounding) },             // ImGuiStyleVar_PopupRounding
3342
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, PopupBorderSize) },           // ImGuiStyleVar_PopupBorderSize
3343
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, FramePadding) },              // ImGuiStyleVar_FramePadding
3344
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, FrameRounding) },             // ImGuiStyleVar_FrameRounding
3345
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, FrameBorderSize) },           // ImGuiStyleVar_FrameBorderSize
3346
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, ItemSpacing) },               // ImGuiStyleVar_ItemSpacing
3347
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, ItemInnerSpacing) },          // ImGuiStyleVar_ItemInnerSpacing
3348
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, IndentSpacing) },             // ImGuiStyleVar_IndentSpacing
3349
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, CellPadding) },               // ImGuiStyleVar_CellPadding
3350
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ScrollbarSize) },             // ImGuiStyleVar_ScrollbarSize
3351
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ScrollbarRounding) },         // ImGuiStyleVar_ScrollbarRounding
3352
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, GrabMinSize) },               // ImGuiStyleVar_GrabMinSize
3353
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, GrabRounding) },              // ImGuiStyleVar_GrabRounding
3354
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabRounding) },               // ImGuiStyleVar_TabRounding
3355
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabBorderSize) },             // ImGuiStyleVar_TabBorderSize
3356
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabBarBorderSize) },          // ImGuiStyleVar_TabBarBorderSize
3357
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabBarOverlineSize) },        // ImGuiStyleVar_TabBarOverlineSize
3358
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TableAngledHeadersAngle)},    // ImGuiStyleVar_TableAngledHeadersAngle
3359
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, TableAngledHeadersTextAlign)},// ImGuiStyleVar_TableAngledHeadersTextAlign
3360
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, ButtonTextAlign) },           // ImGuiStyleVar_ButtonTextAlign
3361
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SelectableTextAlign) },       // ImGuiStyleVar_SelectableTextAlign
3362
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, SeparatorTextBorderSize)},    // ImGuiStyleVar_SeparatorTextBorderSize
3363
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SeparatorTextAlign) },        // ImGuiStyleVar_SeparatorTextAlign
3364
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SeparatorTextPadding) },      // ImGuiStyleVar_SeparatorTextPadding
3365
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, DockingSeparatorSize) },      // ImGuiStyleVar_DockingSeparatorSize
3366
};
3367
3368
const ImGuiDataVarInfo* ImGui::GetStyleVarInfo(ImGuiStyleVar idx)
3369
169k
{
3370
169k
    IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT);
3371
169k
    IM_STATIC_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_COUNT);
3372
169k
    return &GStyleVarInfo[idx];
3373
169k
}
3374
3375
void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
3376
0
{
3377
0
    ImGuiContext& g = *GImGui;
3378
0
    const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx);
3379
0
    if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1)
3380
0
    {
3381
0
        float* pvar = (float*)var_info->GetVarPtr(&g.Style);
3382
0
        g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3383
0
        *pvar = val;
3384
0
        return;
3385
0
    }
3386
0
    IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!");
3387
0
}
3388
3389
void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
3390
84.9k
{
3391
84.9k
    ImGuiContext& g = *GImGui;
3392
84.9k
    const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx);
3393
84.9k
    if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2)
3394
84.9k
    {
3395
84.9k
        ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
3396
84.9k
        g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3397
84.9k
        *pvar = val;
3398
84.9k
        return;
3399
84.9k
    }
3400
0
    IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!");
3401
0
}
3402
3403
void ImGui::PopStyleVar(int count)
3404
84.9k
{
3405
84.9k
    ImGuiContext& g = *GImGui;
3406
84.9k
    if (g.StyleVarStack.Size < count)
3407
0
    {
3408
0
        IM_ASSERT_USER_ERROR(g.StyleVarStack.Size > count, "Calling PopStyleVar() too many times!");
3409
0
        count = g.StyleVarStack.Size;
3410
0
    }
3411
169k
    while (count > 0)
3412
84.9k
    {
3413
        // We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it.
3414
84.9k
        ImGuiStyleMod& backup = g.StyleVarStack.back();
3415
84.9k
        const ImGuiDataVarInfo* info = GetStyleVarInfo(backup.VarIdx);
3416
84.9k
        void* data = info->GetVarPtr(&g.Style);
3417
84.9k
        if (info->Type == ImGuiDataType_Float && info->Count == 1)      { ((float*)data)[0] = backup.BackupFloat[0]; }
3418
84.9k
        else if (info->Type == ImGuiDataType_Float && info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; }
3419
84.9k
        g.StyleVarStack.pop_back();
3420
84.9k
        count--;
3421
84.9k
    }
3422
84.9k
}
3423
3424
const char* ImGui::GetStyleColorName(ImGuiCol idx)
3425
0
{
3426
    // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
3427
0
    switch (idx)
3428
0
    {
3429
0
    case ImGuiCol_Text: return "Text";
3430
0
    case ImGuiCol_TextDisabled: return "TextDisabled";
3431
0
    case ImGuiCol_WindowBg: return "WindowBg";
3432
0
    case ImGuiCol_ChildBg: return "ChildBg";
3433
0
    case ImGuiCol_PopupBg: return "PopupBg";
3434
0
    case ImGuiCol_Border: return "Border";
3435
0
    case ImGuiCol_BorderShadow: return "BorderShadow";
3436
0
    case ImGuiCol_FrameBg: return "FrameBg";
3437
0
    case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
3438
0
    case ImGuiCol_FrameBgActive: return "FrameBgActive";
3439
0
    case ImGuiCol_TitleBg: return "TitleBg";
3440
0
    case ImGuiCol_TitleBgActive: return "TitleBgActive";
3441
0
    case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
3442
0
    case ImGuiCol_MenuBarBg: return "MenuBarBg";
3443
0
    case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
3444
0
    case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
3445
0
    case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
3446
0
    case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
3447
0
    case ImGuiCol_CheckMark: return "CheckMark";
3448
0
    case ImGuiCol_SliderGrab: return "SliderGrab";
3449
0
    case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
3450
0
    case ImGuiCol_Button: return "Button";
3451
0
    case ImGuiCol_ButtonHovered: return "ButtonHovered";
3452
0
    case ImGuiCol_ButtonActive: return "ButtonActive";
3453
0
    case ImGuiCol_Header: return "Header";
3454
0
    case ImGuiCol_HeaderHovered: return "HeaderHovered";
3455
0
    case ImGuiCol_HeaderActive: return "HeaderActive";
3456
0
    case ImGuiCol_Separator: return "Separator";
3457
0
    case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
3458
0
    case ImGuiCol_SeparatorActive: return "SeparatorActive";
3459
0
    case ImGuiCol_ResizeGrip: return "ResizeGrip";
3460
0
    case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
3461
0
    case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
3462
0
    case ImGuiCol_TabHovered: return "TabHovered";
3463
0
    case ImGuiCol_Tab: return "Tab";
3464
0
    case ImGuiCol_TabSelected: return "TabSelected";
3465
0
    case ImGuiCol_TabSelectedOverline: return "TabSelectedOverline";
3466
0
    case ImGuiCol_TabDimmed: return "TabDimmed";
3467
0
    case ImGuiCol_TabDimmedSelected: return "TabDimmedSelected";
3468
0
    case ImGuiCol_TabDimmedSelectedOverline: return "TabDimmedSelectedOverline";
3469
0
    case ImGuiCol_DockingPreview: return "DockingPreview";
3470
0
    case ImGuiCol_DockingEmptyBg: return "DockingEmptyBg";
3471
0
    case ImGuiCol_PlotLines: return "PlotLines";
3472
0
    case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
3473
0
    case ImGuiCol_PlotHistogram: return "PlotHistogram";
3474
0
    case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
3475
0
    case ImGuiCol_TableHeaderBg: return "TableHeaderBg";
3476
0
    case ImGuiCol_TableBorderStrong: return "TableBorderStrong";
3477
0
    case ImGuiCol_TableBorderLight: return "TableBorderLight";
3478
0
    case ImGuiCol_TableRowBg: return "TableRowBg";
3479
0
    case ImGuiCol_TableRowBgAlt: return "TableRowBgAlt";
3480
0
    case ImGuiCol_TextLink: return "TextLink";
3481
0
    case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
3482
0
    case ImGuiCol_DragDropTarget: return "DragDropTarget";
3483
0
    case ImGuiCol_NavHighlight: return "NavHighlight";
3484
0
    case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
3485
0
    case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg";
3486
0
    case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg";
3487
0
    }
3488
0
    IM_ASSERT(0);
3489
0
    return "Unknown";
3490
0
}
3491
3492
3493
//-----------------------------------------------------------------------------
3494
// [SECTION] RENDER HELPERS
3495
// Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change,
3496
// we need a nicer separation between low-level functions and high-level functions relying on the ImGui context.
3497
// Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: context.
3498
//-----------------------------------------------------------------------------
3499
3500
const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
3501
339k
{
3502
339k
    const char* text_display_end = text;
3503
339k
    if (!text_end)
3504
339k
        text_end = (const char*)-1;
3505
3506
3.05M
    while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
3507
2.71M
        text_display_end++;
3508
339k
    return text_display_end;
3509
339k
}
3510
3511
// Internal ImGui functions to render text
3512
// RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
3513
void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
3514
0
{
3515
0
    ImGuiContext& g = *GImGui;
3516
0
    ImGuiWindow* window = g.CurrentWindow;
3517
3518
    // Hide anything after a '##' string
3519
0
    const char* text_display_end;
3520
0
    if (hide_text_after_hash)
3521
0
    {
3522
0
        text_display_end = FindRenderedTextEnd(text, text_end);
3523
0
    }
3524
0
    else
3525
0
    {
3526
0
        if (!text_end)
3527
0
            text_end = text + strlen(text); // FIXME-OPT
3528
0
        text_display_end = text_end;
3529
0
    }
3530
3531
0
    if (text != text_display_end)
3532
0
    {
3533
0
        window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end);
3534
0
        if (g.LogEnabled)
3535
0
            LogRenderedText(&pos, text, text_display_end);
3536
0
    }
3537
0
}
3538
3539
void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
3540
0
{
3541
0
    ImGuiContext& g = *GImGui;
3542
0
    ImGuiWindow* window = g.CurrentWindow;
3543
3544
0
    if (!text_end)
3545
0
        text_end = text + strlen(text); // FIXME-OPT
3546
3547
0
    if (text != text_end)
3548
0
    {
3549
0
        window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width);
3550
0
        if (g.LogEnabled)
3551
0
            LogRenderedText(&pos, text, text_end);
3552
0
    }
3553
0
}
3554
3555
// Default clip_rect uses (pos_min,pos_max)
3556
// Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
3557
// FIXME-OPT: Since we have or calculate text_size we could coarse clip whole block immediately, especally for text above draw_list->DrawList.
3558
// Effectively as this is called from widget doing their own coarse clipping it's not very valuable presently. Next time function will take
3559
// better advantage of the render function taking size into account for coarse clipping.
3560
void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_display_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
3561
169k
{
3562
    // Perform CPU side clipping for single clipped element to avoid using scissor state
3563
169k
    ImVec2 pos = pos_min;
3564
169k
    const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f);
3565
3566
169k
    const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;
3567
169k
    const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;
3568
169k
    bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
3569
169k
    if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min
3570
169k
        need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
3571
3572
    // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
3573
169k
    if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x);
3574
169k
    if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y);
3575
3576
    // Render
3577
169k
    if (need_clipping)
3578
1
    {
3579
1
        ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
3580
1
        draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);
3581
1
    }
3582
169k
    else
3583
169k
    {
3584
169k
        draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
3585
169k
    }
3586
169k
}
3587
3588
void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
3589
169k
{
3590
    // Hide anything after a '##' string
3591
169k
    const char* text_display_end = FindRenderedTextEnd(text, text_end);
3592
169k
    const int text_len = (int)(text_display_end - text);
3593
169k
    if (text_len == 0)
3594
0
        return;
3595
3596
169k
    ImGuiContext& g = *GImGui;
3597
169k
    ImGuiWindow* window = g.CurrentWindow;
3598
169k
    RenderTextClippedEx(window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect);
3599
169k
    if (g.LogEnabled)
3600
0
        LogRenderedText(&pos_min, text, text_display_end);
3601
169k
}
3602
3603
// Another overly complex function until we reorganize everything into a nice all-in-one helper.
3604
// This is made more complex because we have dissociated the layout rectangle (pos_min..pos_max) which define _where_ the ellipsis is, from actual clipping of text and limit of the ellipsis display.
3605
// This is because in the context of tabs we selectively hide part of the text when the Close Button appears, but we don't want the ellipsis to move.
3606
void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float clip_max_x, float ellipsis_max_x, const char* text, const char* text_end_full, const ImVec2* text_size_if_known)
3607
0
{
3608
0
    ImGuiContext& g = *GImGui;
3609
0
    if (text_end_full == NULL)
3610
0
        text_end_full = FindRenderedTextEnd(text);
3611
0
    const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end_full, false, 0.0f);
3612
3613
    //draw_list->AddLine(ImVec2(pos_max.x, pos_min.y - 4), ImVec2(pos_max.x, pos_max.y + 4), IM_COL32(0, 0, 255, 255));
3614
    //draw_list->AddLine(ImVec2(ellipsis_max_x, pos_min.y-2), ImVec2(ellipsis_max_x, pos_max.y+2), IM_COL32(0, 255, 0, 255));
3615
    //draw_list->AddLine(ImVec2(clip_max_x, pos_min.y), ImVec2(clip_max_x, pos_max.y), IM_COL32(255, 0, 0, 255));
3616
    // FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels.
3617
0
    if (text_size.x > pos_max.x - pos_min.x)
3618
0
    {
3619
        // Hello wo...
3620
        // |       |   |
3621
        // min   max   ellipsis_max
3622
        //          <-> this is generally some padding value
3623
3624
0
        const ImFont* font = draw_list->_Data->Font;
3625
0
        const float font_size = draw_list->_Data->FontSize;
3626
0
        const float font_scale = draw_list->_Data->FontScale;
3627
0
        const char* text_end_ellipsis = NULL;
3628
0
        const float ellipsis_width = font->EllipsisWidth * font_scale;
3629
3630
        // We can now claim the space between pos_max.x and ellipsis_max.x
3631
0
        const float text_avail_width = ImMax((ImMax(pos_max.x, ellipsis_max_x) - ellipsis_width) - pos_min.x, 1.0f);
3632
0
        float text_size_clipped_x = font->CalcTextSizeA(font_size, text_avail_width, 0.0f, text, text_end_full, &text_end_ellipsis).x;
3633
0
        if (text == text_end_ellipsis && text_end_ellipsis < text_end_full)
3634
0
        {
3635
            // Always display at least 1 character if there's no room for character + ellipsis
3636
0
            text_end_ellipsis = text + ImTextCountUtf8BytesFromChar(text, text_end_full);
3637
0
            text_size_clipped_x = font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text, text_end_ellipsis).x;
3638
0
        }
3639
0
        while (text_end_ellipsis > text && ImCharIsBlankA(text_end_ellipsis[-1]))
3640
0
        {
3641
            // Trim trailing space before ellipsis (FIXME: Supporting non-ascii blanks would be nice, for this we need a function to backtrack in UTF-8 text)
3642
0
            text_end_ellipsis--;
3643
0
            text_size_clipped_x -= font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text_end_ellipsis, text_end_ellipsis + 1).x; // Ascii blanks are always 1 byte
3644
0
        }
3645
3646
        // Render text, render ellipsis
3647
0
        RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f));
3648
0
        ImVec2 ellipsis_pos = ImTrunc(ImVec2(pos_min.x + text_size_clipped_x, pos_min.y));
3649
0
        if (ellipsis_pos.x + ellipsis_width <= ellipsis_max_x)
3650
0
            for (int i = 0; i < font->EllipsisCharCount; i++, ellipsis_pos.x += font->EllipsisCharStep * font_scale)
3651
0
                font->RenderChar(draw_list, font_size, ellipsis_pos, GetColorU32(ImGuiCol_Text), font->EllipsisChar);
3652
0
    }
3653
0
    else
3654
0
    {
3655
0
        RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_full, &text_size, ImVec2(0.0f, 0.0f));
3656
0
    }
3657
3658
0
    if (g.LogEnabled)
3659
0
        LogRenderedText(&pos_min, text, text_end_full);
3660
0
}
3661
3662
// Render a rectangle shaped with optional rounding and borders
3663
void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding)
3664
61.2k
{
3665
61.2k
    ImGuiContext& g = *GImGui;
3666
61.2k
    ImGuiWindow* window = g.CurrentWindow;
3667
61.2k
    window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);
3668
61.2k
    const float border_size = g.Style.FrameBorderSize;
3669
61.2k
    if (border && border_size > 0.0f)
3670
61.2k
    {
3671
61.2k
        window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
3672
61.2k
        window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
3673
61.2k
    }
3674
61.2k
}
3675
3676
void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
3677
0
{
3678
0
    ImGuiContext& g = *GImGui;
3679
0
    ImGuiWindow* window = g.CurrentWindow;
3680
0
    const float border_size = g.Style.FrameBorderSize;
3681
0
    if (border_size > 0.0f)
3682
0
    {
3683
0
        window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
3684
0
        window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
3685
0
    }
3686
0
}
3687
3688
void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags)
3689
202k
{
3690
202k
    ImGuiContext& g = *GImGui;
3691
202k
    if (id != g.NavId)
3692
186k
        return;
3693
16.3k
    if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw))
3694
313
        return;
3695
16.0k
    ImGuiWindow* window = g.CurrentWindow;
3696
16.0k
    if (window->DC.NavHideHighlightOneFrame)
3697
0
        return;
3698
3699
16.0k
    float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding;
3700
16.0k
    ImRect display_rect = bb;
3701
16.0k
    display_rect.ClipWith(window->ClipRect);
3702
16.0k
    const float thickness = 2.0f;
3703
16.0k
    if (flags & ImGuiNavHighlightFlags_Compact)
3704
14.0k
    {
3705
14.0k
        window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, 0, thickness);
3706
14.0k
    }
3707
1.93k
    else
3708
1.93k
    {
3709
1.93k
        const float distance = 3.0f + thickness * 0.5f;
3710
1.93k
        display_rect.Expand(ImVec2(distance, distance));
3711
1.93k
        bool fully_visible = window->ClipRect.Contains(display_rect);
3712
1.93k
        if (!fully_visible)
3713
107
            window->DrawList->PushClipRect(display_rect.Min, display_rect.Max);
3714
1.93k
        window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, 0, thickness);
3715
1.93k
        if (!fully_visible)
3716
107
            window->DrawList->PopClipRect();
3717
1.93k
    }
3718
16.0k
}
3719
3720
void ImGui::RenderMouseCursor(ImVec2 base_pos, float base_scale, ImGuiMouseCursor mouse_cursor, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow)
3721
0
{
3722
0
    ImGuiContext& g = *GImGui;
3723
0
    IM_ASSERT(mouse_cursor > ImGuiMouseCursor_None && mouse_cursor < ImGuiMouseCursor_COUNT);
3724
0
    ImFontAtlas* font_atlas = g.DrawListSharedData.Font->ContainerAtlas;
3725
0
    for (ImGuiViewportP* viewport : g.Viewports)
3726
0
    {
3727
        // We scale cursor with current viewport/monitor, however Windows 10 for its own hardware cursor seems to be using a different scale factor.
3728
0
        ImVec2 offset, size, uv[4];
3729
0
        if (!font_atlas->GetMouseCursorTexData(mouse_cursor, &offset, &size, &uv[0], &uv[2]))
3730
0
            continue;
3731
0
        const ImVec2 pos = base_pos - offset;
3732
0
        const float scale = base_scale * viewport->DpiScale;
3733
0
        if (!viewport->GetMainRect().Overlaps(ImRect(pos, pos + ImVec2(size.x + 2, size.y + 2) * scale)))
3734
0
            continue;
3735
0
        ImDrawList* draw_list = GetForegroundDrawList(viewport);
3736
0
        ImTextureID tex_id = font_atlas->TexID;
3737
0
        draw_list->PushTextureID(tex_id);
3738
0
        draw_list->AddImage(tex_id, pos + ImVec2(1, 0) * scale, pos + (ImVec2(1, 0) + size) * scale, uv[2], uv[3], col_shadow);
3739
0
        draw_list->AddImage(tex_id, pos + ImVec2(2, 0) * scale, pos + (ImVec2(2, 0) + size) * scale, uv[2], uv[3], col_shadow);
3740
0
        draw_list->AddImage(tex_id, pos,                        pos + size * scale,                  uv[2], uv[3], col_border);
3741
0
        draw_list->AddImage(tex_id, pos,                        pos + size * scale,                  uv[0], uv[1], col_fill);
3742
0
        draw_list->PopTextureID();
3743
0
    }
3744
0
}
3745
3746
//-----------------------------------------------------------------------------
3747
// [SECTION] INITIALIZATION, SHUTDOWN
3748
//-----------------------------------------------------------------------------
3749
3750
// Internal state access - if you want to share Dear ImGui state between modules (e.g. DLL) or allocate it yourself
3751
// Note that we still point to some static data and members (such as GFontAtlas), so the state instance you end up using will point to the static data within its module
3752
ImGuiContext* ImGui::GetCurrentContext()
3753
1
{
3754
1
    return GImGui;
3755
1
}
3756
3757
void ImGui::SetCurrentContext(ImGuiContext* ctx)
3758
1
{
3759
#ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC
3760
    IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.
3761
#else
3762
1
    GImGui = ctx;
3763
1
#endif
3764
1
}
3765
3766
void ImGui::SetAllocatorFunctions(ImGuiMemAllocFunc alloc_func, ImGuiMemFreeFunc free_func, void* user_data)
3767
0
{
3768
0
    GImAllocatorAllocFunc = alloc_func;
3769
0
    GImAllocatorFreeFunc = free_func;
3770
0
    GImAllocatorUserData = user_data;
3771
0
}
3772
3773
// This is provided to facilitate copying allocators from one static/DLL boundary to another (e.g. retrieve default allocator of your executable address space)
3774
void ImGui::GetAllocatorFunctions(ImGuiMemAllocFunc* p_alloc_func, ImGuiMemFreeFunc* p_free_func, void** p_user_data)
3775
0
{
3776
0
    *p_alloc_func = GImAllocatorAllocFunc;
3777
0
    *p_free_func = GImAllocatorFreeFunc;
3778
0
    *p_user_data = GImAllocatorUserData;
3779
0
}
3780
3781
ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas)
3782
1
{
3783
1
    ImGuiContext* prev_ctx = GetCurrentContext();
3784
1
    ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas);
3785
1
    SetCurrentContext(ctx);
3786
1
    Initialize();
3787
1
    if (prev_ctx != NULL)
3788
0
        SetCurrentContext(prev_ctx); // Restore previous context if any, else keep new one.
3789
1
    return ctx;
3790
1
}
3791
3792
void ImGui::DestroyContext(ImGuiContext* ctx)
3793
0
{
3794
0
    ImGuiContext* prev_ctx = GetCurrentContext();
3795
0
    if (ctx == NULL) //-V1051
3796
0
        ctx = prev_ctx;
3797
0
    SetCurrentContext(ctx);
3798
0
    Shutdown();
3799
0
    SetCurrentContext((prev_ctx != ctx) ? prev_ctx : NULL);
3800
0
    IM_DELETE(ctx);
3801
0
}
3802
3803
// IMPORTANT: ###xxx suffixes must be same in ALL languages to allow for automation.
3804
static const ImGuiLocEntry GLocalizationEntriesEnUS[] =
3805
{
3806
    { ImGuiLocKey_VersionStr,           "Dear ImGui " IMGUI_VERSION " (" IM_STRINGIFY(IMGUI_VERSION_NUM) ")" },
3807
    { ImGuiLocKey_TableSizeOne,         "Size column to fit###SizeOne"          },
3808
    { ImGuiLocKey_TableSizeAllFit,      "Size all columns to fit###SizeAll"     },
3809
    { ImGuiLocKey_TableSizeAllDefault,  "Size all columns to default###SizeAll" },
3810
    { ImGuiLocKey_TableResetOrder,      "Reset order###ResetOrder"              },
3811
    { ImGuiLocKey_WindowingMainMenuBar, "(Main menu bar)"                       },
3812
    { ImGuiLocKey_WindowingPopup,       "(Popup)"                               },
3813
    { ImGuiLocKey_WindowingUntitled,    "(Untitled)"                            },
3814
    { ImGuiLocKey_CopyLink,             "Copy Link###CopyLink"                  },
3815
    { ImGuiLocKey_DockingHideTabBar,    "Hide tab bar###HideTabBar"             },
3816
    { ImGuiLocKey_DockingHoldShiftToDock,       "Hold SHIFT to enable Docking window."  },
3817
    { ImGuiLocKey_DockingDragToUndockOrMoveNode,"Click and drag to move or undock whole node."    },
3818
};
3819
3820
void ImGui::Initialize()
3821
1
{
3822
1
    ImGuiContext& g = *GImGui;
3823
1
    IM_ASSERT(!g.Initialized && !g.SettingsLoaded);
3824
3825
    // Add .ini handle for ImGuiWindow and ImGuiTable types
3826
1
    {
3827
1
        ImGuiSettingsHandler ini_handler;
3828
1
        ini_handler.TypeName = "Window";
3829
1
        ini_handler.TypeHash = ImHashStr("Window");
3830
1
        ini_handler.ClearAllFn = WindowSettingsHandler_ClearAll;
3831
1
        ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen;
3832
1
        ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine;
3833
1
        ini_handler.ApplyAllFn = WindowSettingsHandler_ApplyAll;
3834
1
        ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll;
3835
1
        AddSettingsHandler(&ini_handler);
3836
1
    }
3837
1
    TableSettingsAddSettingsHandler();
3838
3839
    // Setup default localization table
3840
1
    LocalizeRegisterEntries(GLocalizationEntriesEnUS, IM_ARRAYSIZE(GLocalizationEntriesEnUS));
3841
3842
    // Setup default platform clipboard/IME handlers.
3843
1
    g.IO.GetClipboardTextFn = GetClipboardTextFn_DefaultImpl;    // Platform dependent default implementations
3844
1
    g.IO.SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
3845
1
    g.IO.ClipboardUserData = (void*)&g;                          // Default implementation use the ImGuiContext as user data (ideally those would be arguments to the function)
3846
1
    g.IO.PlatformOpenInShellFn = PlatformOpenInShellFn_DefaultImpl;
3847
1
    g.IO.PlatformSetImeDataFn = PlatformSetImeDataFn_DefaultImpl;
3848
3849
    // Create default viewport
3850
1
    ImGuiViewportP* viewport = IM_NEW(ImGuiViewportP)();
3851
1
    viewport->ID = IMGUI_VIEWPORT_DEFAULT_ID;
3852
1
    viewport->Idx = 0;
3853
1
    viewport->PlatformWindowCreated = true;
3854
1
    viewport->Flags = ImGuiViewportFlags_OwnedByApp;
3855
1
    g.Viewports.push_back(viewport);
3856
1
    g.TempBuffer.resize(1024 * 3 + 1, 0);
3857
1
    g.ViewportCreatedCount++;
3858
1
    g.PlatformIO.Viewports.push_back(g.Viewports[0]);
3859
3860
    // Build KeysMayBeCharInput[] lookup table (1 bool per named key)
3861
155
    for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
3862
154
        if ((key >= ImGuiKey_0 && key <= ImGuiKey_9) || (key >= ImGuiKey_A && key <= ImGuiKey_Z) || (key >= ImGuiKey_Keypad0 && key <= ImGuiKey_Keypad9)
3863
154
            || key == ImGuiKey_Tab || key == ImGuiKey_Space || key == ImGuiKey_Apostrophe || key == ImGuiKey_Comma || key == ImGuiKey_Minus || key == ImGuiKey_Period
3864
154
            || key == ImGuiKey_Slash || key == ImGuiKey_Semicolon || key == ImGuiKey_Equal || key == ImGuiKey_LeftBracket || key == ImGuiKey_RightBracket || key == ImGuiKey_GraveAccent
3865
154
            || key == ImGuiKey_KeypadDecimal || key == ImGuiKey_KeypadDivide || key == ImGuiKey_KeypadMultiply || key == ImGuiKey_KeypadSubtract || key == ImGuiKey_KeypadAdd || key == ImGuiKey_KeypadEqual)
3866
64
            g.KeysMayBeCharInput.SetBit(key);
3867
3868
1
#ifdef IMGUI_HAS_DOCK
3869
    // Initialize Docking
3870
1
    DockContextInitialize(&g);
3871
1
#endif
3872
3873
1
    g.Initialized = true;
3874
1
}
3875
3876
// This function is merely here to free heap allocations.
3877
void ImGui::Shutdown()
3878
0
{
3879
0
    ImGuiContext& g = *GImGui;
3880
0
    IM_ASSERT_USER_ERROR(g.IO.BackendPlatformUserData == NULL, "Forgot to shutdown Platform backend?");
3881
0
    IM_ASSERT_USER_ERROR(g.IO.BackendRendererUserData == NULL, "Forgot to shutdown Renderer backend?");
3882
3883
    // The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame)
3884
0
    if (g.IO.Fonts && g.FontAtlasOwnedByContext)
3885
0
    {
3886
0
        g.IO.Fonts->Locked = false;
3887
0
        IM_DELETE(g.IO.Fonts);
3888
0
    }
3889
0
    g.IO.Fonts = NULL;
3890
0
    g.DrawListSharedData.TempBuffer.clear();
3891
3892
    // Cleanup of other data are conditional on actually having initialized Dear ImGui.
3893
0
    if (!g.Initialized)
3894
0
        return;
3895
3896
    // Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file)
3897
0
    if (g.SettingsLoaded && g.IO.IniFilename != NULL)
3898
0
        SaveIniSettingsToDisk(g.IO.IniFilename);
3899
3900
    // Destroy platform windows
3901
0
    DestroyPlatformWindows();
3902
3903
    // Shutdown extensions
3904
0
    DockContextShutdown(&g);
3905
3906
0
    CallContextHooks(&g, ImGuiContextHookType_Shutdown);
3907
3908
    // Clear everything else
3909
0
    g.Windows.clear_delete();
3910
0
    g.WindowsFocusOrder.clear();
3911
0
    g.WindowsTempSortBuffer.clear();
3912
0
    g.CurrentWindow = NULL;
3913
0
    g.CurrentWindowStack.clear();
3914
0
    g.WindowsById.Clear();
3915
0
    g.NavWindow = NULL;
3916
0
    g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
3917
0
    g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL;
3918
0
    g.MovingWindow = NULL;
3919
3920
0
    g.KeysRoutingTable.Clear();
3921
3922
0
    g.ColorStack.clear();
3923
0
    g.StyleVarStack.clear();
3924
0
    g.FontStack.clear();
3925
0
    g.OpenPopupStack.clear();
3926
0
    g.BeginPopupStack.clear();
3927
0
    g.TreeNodeStack.clear();
3928
3929
0
    g.CurrentViewport = g.MouseViewport = g.MouseLastHoveredViewport = NULL;
3930
0
    g.Viewports.clear_delete();
3931
3932
0
    g.TabBars.Clear();
3933
0
    g.CurrentTabBarStack.clear();
3934
0
    g.ShrinkWidthBuffer.clear();
3935
3936
0
    g.ClipperTempData.clear_destruct();
3937
3938
0
    g.Tables.Clear();
3939
0
    g.TablesTempData.clear_destruct();
3940
0
    g.DrawChannelsTempMergeBuffer.clear();
3941
3942
0
    g.MultiSelectStorage.Clear();
3943
0
    g.MultiSelectTempData.clear_destruct();
3944
3945
0
    g.ClipboardHandlerData.clear();
3946
0
    g.MenusIdSubmittedThisFrame.clear();
3947
0
    g.InputTextState.ClearFreeMemory();
3948
0
    g.InputTextDeactivatedState.ClearFreeMemory();
3949
3950
0
    g.SettingsWindows.clear();
3951
0
    g.SettingsHandlers.clear();
3952
3953
0
    if (g.LogFile)
3954
0
    {
3955
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
3956
0
        if (g.LogFile != stdout)
3957
0
#endif
3958
0
            ImFileClose(g.LogFile);
3959
0
        g.LogFile = NULL;
3960
0
    }
3961
0
    g.LogBuffer.clear();
3962
0
    g.DebugLogBuf.clear();
3963
0
    g.DebugLogIndex.clear();
3964
3965
0
    g.Initialized = false;
3966
0
}
3967
3968
// No specific ordering/dependency support, will see as needed
3969
ImGuiID ImGui::AddContextHook(ImGuiContext* ctx, const ImGuiContextHook* hook)
3970
0
{
3971
0
    ImGuiContext& g = *ctx;
3972
0
    IM_ASSERT(hook->Callback != NULL && hook->HookId == 0 && hook->Type != ImGuiContextHookType_PendingRemoval_);
3973
0
    g.Hooks.push_back(*hook);
3974
0
    g.Hooks.back().HookId = ++g.HookIdNext;
3975
0
    return g.HookIdNext;
3976
0
}
3977
3978
// Deferred removal, avoiding issue with changing vector while iterating it
3979
void ImGui::RemoveContextHook(ImGuiContext* ctx, ImGuiID hook_id)
3980
0
{
3981
0
    ImGuiContext& g = *ctx;
3982
0
    IM_ASSERT(hook_id != 0);
3983
0
    for (ImGuiContextHook& hook : g.Hooks)
3984
0
        if (hook.HookId == hook_id)
3985
0
            hook.Type = ImGuiContextHookType_PendingRemoval_;
3986
0
}
3987
3988
// Call context hooks (used by e.g. test engine)
3989
// We assume a small number of hooks so all stored in same array
3990
void ImGui::CallContextHooks(ImGuiContext* ctx, ImGuiContextHookType hook_type)
3991
509k
{
3992
509k
    ImGuiContext& g = *ctx;
3993
509k
    for (ImGuiContextHook& hook : g.Hooks)
3994
0
        if (hook.Type == hook_type)
3995
0
            hook.Callback(&g, &hook);
3996
509k
}
3997
3998
3999
//-----------------------------------------------------------------------------
4000
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
4001
//-----------------------------------------------------------------------------
4002
4003
// ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods
4004
ImGuiWindow::ImGuiWindow(ImGuiContext* ctx, const char* name) : DrawListInst(NULL)
4005
3
{
4006
3
    memset(this, 0, sizeof(*this));
4007
3
    Ctx = ctx;
4008
3
    Name = ImStrdup(name);
4009
3
    NameBufLen = (int)strlen(name) + 1;
4010
3
    ID = ImHashStr(name);
4011
3
    IDStack.push_back(ID);
4012
3
    ViewportAllowPlatformMonitorExtend = -1;
4013
3
    ViewportPos = ImVec2(FLT_MAX, FLT_MAX);
4014
3
    MoveId = GetID("#MOVE");
4015
3
    TabId = GetID("#TAB");
4016
3
    ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
4017
3
    ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
4018
3
    AutoFitFramesX = AutoFitFramesY = -1;
4019
3
    AutoPosLastDirection = ImGuiDir_None;
4020
3
    SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = SetWindowDockAllowFlags = 0;
4021
3
    SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
4022
3
    LastFrameActive = -1;
4023
3
    LastFrameJustFocused = -1;
4024
3
    LastTimeActive = -1.0f;
4025
3
    FontWindowScale = FontDpiScale = 1.0f;
4026
3
    SettingsOffset = -1;
4027
3
    DockOrder = -1;
4028
3
    DrawList = &DrawListInst;
4029
3
    DrawList->_Data = &Ctx->DrawListSharedData;
4030
3
    DrawList->_OwnerName = Name;
4031
3
    NavPreferredScoringPosRel[0] = NavPreferredScoringPosRel[1] = ImVec2(FLT_MAX, FLT_MAX);
4032
3
    IM_PLACEMENT_NEW(&WindowClass) ImGuiWindowClass();
4033
3
}
4034
4035
ImGuiWindow::~ImGuiWindow()
4036
0
{
4037
0
    IM_ASSERT(DrawList == &DrawListInst);
4038
0
    IM_DELETE(Name);
4039
0
    ColumnsStorage.clear_destruct();
4040
0
}
4041
4042
static void SetCurrentWindow(ImGuiWindow* window)
4043
387k
{
4044
387k
    ImGuiContext& g = *GImGui;
4045
387k
    g.CurrentWindow = window;
4046
387k
    g.CurrentTable = window && window->DC.CurrentTableIdx != -1 ? g.Tables.GetByIndex(window->DC.CurrentTableIdx) : NULL;
4047
387k
    if (window)
4048
302k
    {
4049
302k
        g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
4050
302k
        g.FontScale = g.FontSize / g.Font->FontSize;
4051
302k
        ImGui::NavUpdateCurrentWindowIsScrollPushableX();
4052
302k
    }
4053
387k
}
4054
4055
void ImGui::GcCompactTransientMiscBuffers()
4056
0
{
4057
0
    ImGuiContext& g = *GImGui;
4058
0
    g.ItemFlagsStack.clear();
4059
0
    g.GroupStack.clear();
4060
0
    g.MultiSelectTempDataStacked = 0;
4061
0
    g.MultiSelectTempData.clear_destruct();
4062
0
    TableGcCompactSettings();
4063
0
}
4064
4065
// Free up/compact internal window buffers, we can use this when a window becomes unused.
4066
// Not freed:
4067
// - ImGuiWindow, ImGuiWindowSettings, Name, StateStorage, ColumnsStorage (may hold useful data)
4068
// This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost.
4069
void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window)
4070
1
{
4071
1
    window->MemoryCompacted = true;
4072
1
    window->MemoryDrawListIdxCapacity = window->DrawList->IdxBuffer.Capacity;
4073
1
    window->MemoryDrawListVtxCapacity = window->DrawList->VtxBuffer.Capacity;
4074
1
    window->IDStack.clear();
4075
1
    window->DrawList->_ClearFreeMemory();
4076
1
    window->DC.ChildWindows.clear();
4077
1
    window->DC.ItemWidthStack.clear();
4078
1
    window->DC.TextWrapPosStack.clear();
4079
1
}
4080
4081
void ImGui::GcAwakeTransientWindowBuffers(ImGuiWindow* window)
4082
0
{
4083
    // We stored capacity of the ImDrawList buffer to reduce growth-caused allocation/copy when awakening.
4084
    // The other buffers tends to amortize much faster.
4085
0
    window->MemoryCompacted = false;
4086
0
    window->DrawList->IdxBuffer.reserve(window->MemoryDrawListIdxCapacity);
4087
0
    window->DrawList->VtxBuffer.reserve(window->MemoryDrawListVtxCapacity);
4088
0
    window->MemoryDrawListIdxCapacity = window->MemoryDrawListVtxCapacity = 0;
4089
0
}
4090
4091
void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
4092
156
{
4093
156
    ImGuiContext& g = *GImGui;
4094
4095
    // Clear previous active id
4096
156
    if (g.ActiveId != 0)
4097
30
    {
4098
        // While most behaved code would make an effort to not steal active id during window move/drag operations,
4099
        // we at least need to be resilient to it. Canceling the move is rather aggressive and users of 'master' branch
4100
        // may prefer the weird ill-defined half working situation ('docking' did assert), so may need to rework that.
4101
30
        if (g.MovingWindow != NULL && g.ActiveId == g.MovingWindow->MoveId)
4102
0
        {
4103
0
            IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() cancel MovingWindow\n");
4104
0
            g.MovingWindow = NULL;
4105
0
        }
4106
4107
        // This could be written in a more general way (e.g associate a hook to ActiveId),
4108
        // but since this is currently quite an exception we'll leave it as is.
4109
        // One common scenario leading to this is: pressing Key ->NavMoveRequestApplyResult() -> ClearActiveId()
4110
30
        if (g.InputTextState.ID == g.ActiveId)
4111
0
            InputTextDeactivateHook(g.ActiveId);
4112
30
    }
4113
4114
    // Set active id
4115
156
    g.ActiveIdIsJustActivated = (g.ActiveId != id);
4116
156
    if (g.ActiveIdIsJustActivated)
4117
60
    {
4118
60
        IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() old:0x%08X (window \"%s\") -> new:0x%08X (window \"%s\")\n", g.ActiveId, g.ActiveIdWindow ? g.ActiveIdWindow->Name : "", id, window ? window->Name : "");
4119
60
        g.ActiveIdTimer = 0.0f;
4120
60
        g.ActiveIdHasBeenPressedBefore = false;
4121
60
        g.ActiveIdHasBeenEditedBefore = false;
4122
60
        g.ActiveIdMouseButton = -1;
4123
60
        if (id != 0)
4124
30
        {
4125
30
            g.LastActiveId = id;
4126
30
            g.LastActiveIdTimer = 0.0f;
4127
30
        }
4128
60
    }
4129
156
    g.ActiveId = id;
4130
156
    g.ActiveIdAllowOverlap = false;
4131
156
    g.ActiveIdNoClearOnFocusLoss = false;
4132
156
    g.ActiveIdWindow = window;
4133
156
    g.ActiveIdHasBeenEditedThisFrame = false;
4134
156
    g.ActiveIdFromShortcut = false;
4135
156
    if (id)
4136
30
    {
4137
30
        g.ActiveIdIsAlive = id;
4138
30
        g.ActiveIdSource = (g.NavActivateId == id || g.NavJustMovedToId == id) ? g.NavInputSource : ImGuiInputSource_Mouse;
4139
30
        IM_ASSERT(g.ActiveIdSource != ImGuiInputSource_None);
4140
30
    }
4141
4142
    // Clear declaration of inputs claimed by the widget
4143
    // (Please note that this is WIP and not all keys/inputs are thoroughly declared by all widgets yet)
4144
156
    g.ActiveIdUsingNavDirMask = 0x00;
4145
156
    g.ActiveIdUsingAllKeyboardKeys = false;
4146
156
}
4147
4148
void ImGui::ClearActiveID()
4149
126
{
4150
126
    SetActiveID(0, NULL); // g.ActiveId = 0;
4151
126
}
4152
4153
void ImGui::SetHoveredID(ImGuiID id)
4154
163
{
4155
163
    ImGuiContext& g = *GImGui;
4156
163
    g.HoveredId = id;
4157
163
    g.HoveredIdAllowOverlap = false;
4158
163
    if (id != 0 && g.HoveredIdPreviousFrame != id)
4159
9
        g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f;
4160
163
}
4161
4162
ImGuiID ImGui::GetHoveredID()
4163
0
{
4164
0
    ImGuiContext& g = *GImGui;
4165
0
    return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame;
4166
0
}
4167
4168
void ImGui::MarkItemEdited(ImGuiID id)
4169
0
{
4170
    // This marking is solely to be able to provide info for IsItemDeactivatedAfterEdit().
4171
    // ActiveId might have been released by the time we call this (as in the typical press/release button behavior) but still need to fill the data.
4172
0
    ImGuiContext& g = *GImGui;
4173
0
    if (g.LockMarkEdited > 0)
4174
0
        return;
4175
0
    if (g.ActiveId == id || g.ActiveId == 0)
4176
0
    {
4177
0
        g.ActiveIdHasBeenEditedThisFrame = true;
4178
0
        g.ActiveIdHasBeenEditedBefore = true;
4179
0
    }
4180
4181
    // We accept a MarkItemEdited() on drag and drop targets (see https://github.com/ocornut/imgui/issues/1875#issuecomment-978243343)
4182
    // We accept 'ActiveIdPreviousFrame == id' for InputText() returning an edit after it has been taken ActiveId away (#4714)
4183
0
    IM_ASSERT(g.DragDropActive || g.ActiveId == id || g.ActiveId == 0 || g.ActiveIdPreviousFrame == id || (g.CurrentMultiSelect != NULL && g.BoxSelectState.IsActive));
4184
4185
    //IM_ASSERT(g.CurrentWindow->DC.LastItemId == id);
4186
0
    g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
4187
0
}
4188
4189
bool ImGui::IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags)
4190
177
{
4191
    // An active popup disable hovering on other windows (apart from its own children)
4192
    // FIXME-OPT: This could be cached/stored within the window.
4193
177
    ImGuiContext& g = *GImGui;
4194
177
    if (g.NavWindow)
4195
29
        if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindowDockTree)
4196
29
            if (focused_root_window->WasActive && focused_root_window != window->RootWindowDockTree)
4197
0
            {
4198
                // For the purpose of those flags we differentiate "standard popup" from "modal popup"
4199
                // NB: The 'else' is important because Modal windows are also Popups.
4200
0
                bool want_inhibit = false;
4201
0
                if (focused_root_window->Flags & ImGuiWindowFlags_Modal)
4202
0
                    want_inhibit = true;
4203
0
                else if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))
4204
0
                    want_inhibit = true;
4205
4206
                // Inhibit hover unless the window is within the stack of our modal/popup
4207
0
                if (want_inhibit)
4208
0
                    if (!IsWindowWithinBeginStackOf(window->RootWindow, focused_root_window))
4209
0
                        return false;
4210
0
            }
4211
4212
    // Filter by viewport
4213
177
    if (window->Viewport != g.MouseViewport)
4214
0
        if (g.MovingWindow == NULL || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree)
4215
0
            return false;
4216
4217
177
    return true;
4218
177
}
4219
4220
static inline float CalcDelayFromHoveredFlags(ImGuiHoveredFlags flags)
4221
0
{
4222
0
    ImGuiContext& g = *GImGui;
4223
0
    if (flags & ImGuiHoveredFlags_DelayNormal)
4224
0
        return g.Style.HoverDelayNormal;
4225
0
    if (flags & ImGuiHoveredFlags_DelayShort)
4226
0
        return g.Style.HoverDelayShort;
4227
0
    return 0.0f;
4228
0
}
4229
4230
static ImGuiHoveredFlags ApplyHoverFlagsForTooltip(ImGuiHoveredFlags user_flags, ImGuiHoveredFlags shared_flags)
4231
0
{
4232
    // Allow instance flags to override shared flags
4233
0
    if (user_flags & (ImGuiHoveredFlags_DelayNone | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_DelayNormal))
4234
0
        shared_flags &= ~(ImGuiHoveredFlags_DelayNone | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_DelayNormal);
4235
0
    return user_flags | shared_flags;
4236
0
}
4237
4238
// This is roughly matching the behavior of internal-facing ItemHoverable()
4239
// - we allow hovering to be true when ActiveId==window->MoveID, so that clicking on non-interactive items such as a Text() item still returns true with IsItemHovered()
4240
// - this should work even for non-interactive items that have no ID, so we cannot use LastItemId
4241
bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
4242
0
{
4243
0
    ImGuiContext& g = *GImGui;
4244
0
    ImGuiWindow* window = g.CurrentWindow;
4245
0
    IM_ASSERT((flags & ~ImGuiHoveredFlags_AllowedMaskForIsItemHovered) == 0 && "Invalid flags for IsItemHovered()!");
4246
4247
0
    if (g.NavDisableMouseHover && !g.NavDisableHighlight && !(flags & ImGuiHoveredFlags_NoNavOverride))
4248
0
    {
4249
0
        if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4250
0
            return false;
4251
0
        if (!IsItemFocused())
4252
0
            return false;
4253
4254
0
        if (flags & ImGuiHoveredFlags_ForTooltip)
4255
0
            flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipNav);
4256
0
    }
4257
0
    else
4258
0
    {
4259
        // Test for bounding box overlap, as updated as ItemAdd()
4260
0
        ImGuiItemStatusFlags status_flags = g.LastItemData.StatusFlags;
4261
0
        if (!(status_flags & ImGuiItemStatusFlags_HoveredRect))
4262
0
            return false;
4263
4264
0
        if (flags & ImGuiHoveredFlags_ForTooltip)
4265
0
            flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipMouse);
4266
4267
0
        IM_ASSERT((flags & (ImGuiHoveredFlags_AnyWindow | ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_NoPopupHierarchy | ImGuiHoveredFlags_DockHierarchy)) == 0);   // Flags not supported by this function
4268
4269
        // Done with rectangle culling so we can perform heavier checks now
4270
        // Test if we are hovering the right window (our window could be behind another window)
4271
        // [2021/03/02] Reworked / reverted the revert, finally. Note we want e.g. BeginGroup/ItemAdd/EndGroup to work as well. (#3851)
4272
        // [2017/10/16] Reverted commit 344d48be3 and testing RootWindow instead. I believe it is correct to NOT test for RootWindow but this leaves us unable
4273
        // to use IsItemHovered() after EndChild() itself. Until a solution is found I believe reverting to the test from 2017/09/27 is safe since this was
4274
        // the test that has been running for a long while.
4275
0
        if (g.HoveredWindow != window && (status_flags & ImGuiItemStatusFlags_HoveredWindow) == 0)
4276
0
            if ((flags & ImGuiHoveredFlags_AllowWhenOverlappedByWindow) == 0)
4277
0
                return false;
4278
4279
        // Test if another item is active (e.g. being dragged)
4280
0
        const ImGuiID id = g.LastItemData.ID;
4281
0
        if ((flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) == 0)
4282
0
            if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
4283
0
                if (g.ActiveId != window->MoveId && g.ActiveId != window->TabId)
4284
0
                    return false;
4285
4286
        // Test if interactions on this window are blocked by an active popup or modal.
4287
        // The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here.
4288
0
        if (!IsWindowContentHoverable(window, flags) && !(g.LastItemData.InFlags & ImGuiItemFlags_NoWindowHoverableCheck))
4289
0
            return false;
4290
4291
        // Test if the item is disabled
4292
0
        if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4293
0
            return false;
4294
4295
        // Special handling for calling after Begin() which represent the title bar or tab.
4296
        // When the window is skipped/collapsed (SkipItems==true) that last item (always ->MoveId submitted by Begin)
4297
        // will never be overwritten so we need to detect the case.
4298
0
        if (id == window->MoveId && window->WriteAccessed)
4299
0
            return false;
4300
4301
        // Test if using AllowOverlap and overlapped
4302
0
        if ((g.LastItemData.InFlags & ImGuiItemFlags_AllowOverlap) && id != 0)
4303
0
            if ((flags & ImGuiHoveredFlags_AllowWhenOverlappedByItem) == 0)
4304
0
                if (g.HoveredIdPreviousFrame != g.LastItemData.ID)
4305
0
                    return false;
4306
0
    }
4307
4308
    // Handle hover delay
4309
    // (some ideas: https://www.nngroup.com/articles/timing-exposing-content)
4310
0
    const float delay = CalcDelayFromHoveredFlags(flags);
4311
0
    if (delay > 0.0f || (flags & ImGuiHoveredFlags_Stationary))
4312
0
    {
4313
0
        ImGuiID hover_delay_id = (g.LastItemData.ID != 0) ? g.LastItemData.ID : window->GetIDFromRectangle(g.LastItemData.Rect);
4314
0
        if ((flags & ImGuiHoveredFlags_NoSharedDelay) && (g.HoverItemDelayIdPreviousFrame != hover_delay_id))
4315
0
            g.HoverItemDelayTimer = 0.0f;
4316
0
        g.HoverItemDelayId = hover_delay_id;
4317
4318
        // When changing hovered item we requires a bit of stationary delay before activating hover timer,
4319
        // but once unlocked on a given item we also moving.
4320
        //if (g.HoverDelayTimer >= delay && (g.HoverDelayTimer - g.IO.DeltaTime < delay || g.MouseStationaryTimer - g.IO.DeltaTime < g.Style.HoverStationaryDelay)) { IMGUI_DEBUG_LOG("HoverDelayTimer = %f/%f, MouseStationaryTimer = %f\n", g.HoverDelayTimer, delay, g.MouseStationaryTimer); }
4321
0
        if ((flags & ImGuiHoveredFlags_Stationary) != 0 && g.HoverItemUnlockedStationaryId != hover_delay_id)
4322
0
            return false;
4323
4324
0
        if (g.HoverItemDelayTimer < delay)
4325
0
            return false;
4326
0
    }
4327
4328
0
    return true;
4329
0
}
4330
4331
// Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered().
4332
// (this does not rely on LastItemData it can be called from a ButtonBehavior() call not following an ItemAdd() call)
4333
// FIXME-LEGACY: the 'ImGuiItemFlags item_flags' parameter was added on 2023-06-28.
4334
// If you used this in your legacy/custom widgets code:
4335
// - Commonly: if your ItemHoverable() call comes after an ItemAdd() call: pass 'item_flags = g.LastItemData.InFlags'.
4336
// - Rare: otherwise you may pass 'item_flags = 0' (ImGuiItemFlags_None) unless you want to benefit from special behavior handled by ItemHoverable.
4337
bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id, ImGuiItemFlags item_flags)
4338
326k
{
4339
326k
    ImGuiContext& g = *GImGui;
4340
326k
    ImGuiWindow* window = g.CurrentWindow;
4341
326k
    if (g.HoveredWindow != window)
4342
324k
        return false;
4343
2.32k
    if (!IsMouseHoveringRect(bb.Min, bb.Max))
4344
2.16k
        return false;
4345
4346
163
    if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap)
4347
0
        return false;
4348
163
    if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
4349
0
        if (!g.ActiveIdFromShortcut)
4350
0
            return false;
4351
4352
    // Done with rectangle culling so we can perform heavier checks now.
4353
163
    if (!(item_flags & ImGuiItemFlags_NoWindowHoverableCheck) && !IsWindowContentHoverable(window, ImGuiHoveredFlags_None))
4354
0
    {
4355
0
        g.HoveredIdIsDisabled = true;
4356
0
        return false;
4357
0
    }
4358
4359
    // We exceptionally allow this function to be called with id==0 to allow using it for easy high-level
4360
    // hover test in widgets code. We could also decide to split this function is two.
4361
163
    if (id != 0)
4362
163
    {
4363
        // Drag source doesn't report as hovered
4364
163
        if (g.DragDropActive && g.DragDropPayload.SourceId == id && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoDisableHover))
4365
0
            return false;
4366
4367
163
        SetHoveredID(id);
4368
4369
        // AllowOverlap mode (rarely used) requires previous frame HoveredId to be null or to match.
4370
        // This allows using patterns where a later submitted widget overlaps a previous one. Generally perceived as a front-to-back hit-test.
4371
163
        if (item_flags & ImGuiItemFlags_AllowOverlap)
4372
0
        {
4373
0
            g.HoveredIdAllowOverlap = true;
4374
0
            if (g.HoveredIdPreviousFrame != id)
4375
0
                return false;
4376
0
        }
4377
4378
        // Display shortcut (only works with mouse)
4379
        // (ImGuiItemStatusFlags_HasShortcut in LastItemData denotes we want a tooltip)
4380
163
        if (id == g.LastItemData.ID && (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasShortcut))
4381
0
            if (IsItemHovered(ImGuiHoveredFlags_ForTooltip | ImGuiHoveredFlags_DelayNormal))
4382
0
                SetTooltip("%s", GetKeyChordName(g.LastItemData.Shortcut));
4383
163
    }
4384
4385
    // When disabled we'll return false but still set HoveredId
4386
163
    if (item_flags & ImGuiItemFlags_Disabled)
4387
0
    {
4388
        // Release active id if turning disabled
4389
0
        if (g.ActiveId == id && id != 0)
4390
0
            ClearActiveID();
4391
0
        g.HoveredIdIsDisabled = true;
4392
0
        return false;
4393
0
    }
4394
4395
163
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4396
163
    if (id != 0)
4397
163
    {
4398
        // [DEBUG] Item Picker tool!
4399
        // We perform the check here because reaching is path is rare (1~ time a frame),
4400
        // making the cost of this tool near-zero! We could get better call-stack and support picking non-hovered
4401
        // items if we performed the test in ItemAdd(), but that would incur a bigger runtime cost.
4402
163
        if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id)
4403
0
            GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
4404
163
        if (g.DebugItemPickerBreakId == id)
4405
0
            IM_DEBUG_BREAK();
4406
163
    }
4407
163
#endif
4408
4409
163
    if (g.NavDisableMouseHover)
4410
18
        return false;
4411
4412
145
    return true;
4413
163
}
4414
4415
// FIXME: This is inlined/duplicated in ItemAdd()
4416
// FIXME: The id != 0 path is not used by our codebase, may get rid of it?
4417
bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id)
4418
0
{
4419
0
    ImGuiContext& g = *GImGui;
4420
0
    ImGuiWindow* window = g.CurrentWindow;
4421
0
    if (!bb.Overlaps(window->ClipRect))
4422
0
        if (id == 0 || (id != g.ActiveId && id != g.ActiveIdPreviousFrame && id != g.NavId && id != g.NavActivateId))
4423
0
            if (!g.ItemUnclipByLog)
4424
0
                return true;
4425
0
    return false;
4426
0
}
4427
4428
// This is also inlined in ItemAdd()
4429
// Note: if ImGuiItemStatusFlags_HasDisplayRect is set, user needs to set g.LastItemData.DisplayRect.
4430
void ImGui::SetLastItemData(ImGuiID item_id, ImGuiItemFlags in_flags, ImGuiItemStatusFlags item_flags, const ImRect& item_rect)
4431
193k
{
4432
193k
    ImGuiContext& g = *GImGui;
4433
193k
    g.LastItemData.ID = item_id;
4434
193k
    g.LastItemData.InFlags = in_flags;
4435
193k
    g.LastItemData.StatusFlags = item_flags;
4436
193k
    g.LastItemData.Rect = g.LastItemData.NavRect = item_rect;
4437
193k
}
4438
4439
float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
4440
0
{
4441
0
    if (wrap_pos_x < 0.0f)
4442
0
        return 0.0f;
4443
4444
0
    ImGuiContext& g = *GImGui;
4445
0
    ImGuiWindow* window = g.CurrentWindow;
4446
0
    if (wrap_pos_x == 0.0f)
4447
0
    {
4448
        // We could decide to setup a default wrapping max point for auto-resizing windows,
4449
        // or have auto-wrap (with unspecified wrapping pos) behave as a ContentSize extending function?
4450
        //if (window->Hidden && (window->Flags & ImGuiWindowFlags_AlwaysAutoResize))
4451
        //    wrap_pos_x = ImMax(window->WorkRect.Min.x + g.FontSize * 10.0f, window->WorkRect.Max.x);
4452
        //else
4453
0
        wrap_pos_x = window->WorkRect.Max.x;
4454
0
    }
4455
0
    else if (wrap_pos_x > 0.0f)
4456
0
    {
4457
0
        wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
4458
0
    }
4459
4460
0
    return ImMax(wrap_pos_x - pos.x, 1.0f);
4461
0
}
4462
4463
// IM_ALLOC() == ImGui::MemAlloc()
4464
void* ImGui::MemAlloc(size_t size)
4465
1.22k
{
4466
1.22k
    void* ptr = (*GImAllocatorAllocFunc)(size, GImAllocatorUserData);
4467
1.22k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4468
1.22k
    if (ImGuiContext* ctx = GImGui)
4469
1.22k
        DebugAllocHook(&ctx->DebugAllocInfo, ctx->FrameCount, ptr, size);
4470
1.22k
#endif
4471
1.22k
    return ptr;
4472
1.22k
}
4473
4474
// IM_FREE() == ImGui::MemFree()
4475
void ImGui::MemFree(void* ptr)
4476
1.17k
{
4477
1.17k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4478
1.17k
    if (ptr != NULL)
4479
1.16k
        if (ImGuiContext* ctx = GImGui)
4480
1.16k
            DebugAllocHook(&ctx->DebugAllocInfo, ctx->FrameCount, ptr, (size_t)-1);
4481
1.17k
#endif
4482
1.17k
    return (*GImAllocatorFreeFunc)(ptr, GImAllocatorUserData);
4483
1.17k
}
4484
4485
// We record the number of allocation in recent frames, as a way to audit/sanitize our guiding principles of "no allocations on idle/repeating frames"
4486
void ImGui::DebugAllocHook(ImGuiDebugAllocInfo* info, int frame_count, void* ptr, size_t size)
4487
2.38k
{
4488
2.38k
    ImGuiDebugAllocEntry* entry = &info->LastEntriesBuf[info->LastEntriesIdx];
4489
2.38k
    IM_UNUSED(ptr);
4490
2.38k
    if (entry->FrameCount != frame_count)
4491
32
    {
4492
32
        info->LastEntriesIdx = (info->LastEntriesIdx + 1) % IM_ARRAYSIZE(info->LastEntriesBuf);
4493
32
        entry = &info->LastEntriesBuf[info->LastEntriesIdx];
4494
32
        entry->FrameCount = frame_count;
4495
32
        entry->AllocCount = entry->FreeCount = 0;
4496
32
    }
4497
2.38k
    if (size != (size_t)-1)
4498
1.22k
    {
4499
1.22k
        entry->AllocCount++;
4500
1.22k
        info->TotalAllocCount++;
4501
        //printf("[%05d] MemAlloc(%d) -> 0x%p\n", frame_count, size, ptr);
4502
1.22k
    }
4503
1.16k
    else
4504
1.16k
    {
4505
1.16k
        entry->FreeCount++;
4506
1.16k
        info->TotalFreeCount++;
4507
        //printf("[%05d] MemFree(0x%p)\n", frame_count, ptr);
4508
1.16k
    }
4509
2.38k
}
4510
4511
const char* ImGui::GetClipboardText()
4512
0
{
4513
0
    ImGuiContext& g = *GImGui;
4514
0
    return g.IO.GetClipboardTextFn ? g.IO.GetClipboardTextFn(g.IO.ClipboardUserData) : "";
4515
0
}
4516
4517
void ImGui::SetClipboardText(const char* text)
4518
0
{
4519
0
    ImGuiContext& g = *GImGui;
4520
0
    if (g.IO.SetClipboardTextFn)
4521
0
        g.IO.SetClipboardTextFn(g.IO.ClipboardUserData, text);
4522
0
}
4523
4524
const char* ImGui::GetVersion()
4525
0
{
4526
0
    return IMGUI_VERSION;
4527
0
}
4528
4529
ImGuiIO& ImGui::GetIO()
4530
247k
{
4531
247k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
4532
247k
    return GImGui->IO;
4533
247k
}
4534
4535
ImGuiPlatformIO& ImGui::GetPlatformIO()
4536
0
{
4537
0
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext()?");
4538
0
    return GImGui->PlatformIO;
4539
0
}
4540
4541
// Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame()
4542
ImDrawData* ImGui::GetDrawData()
4543
84.9k
{
4544
84.9k
    ImGuiContext& g = *GImGui;
4545
84.9k
    ImGuiViewportP* viewport = g.Viewports[0];
4546
84.9k
    return viewport->DrawDataP.Valid ? &viewport->DrawDataP : NULL;
4547
84.9k
}
4548
4549
double ImGui::GetTime()
4550
10
{
4551
10
    return GImGui->Time;
4552
10
}
4553
4554
int ImGui::GetFrameCount()
4555
0
{
4556
0
    return GImGui->FrameCount;
4557
0
}
4558
4559
static ImDrawList* GetViewportBgFgDrawList(ImGuiViewportP* viewport, size_t drawlist_no, const char* drawlist_name)
4560
0
{
4561
    // Create the draw list on demand, because they are not frequently used for all viewports
4562
0
    ImGuiContext& g = *GImGui;
4563
0
    IM_ASSERT(drawlist_no < IM_ARRAYSIZE(viewport->BgFgDrawLists));
4564
0
    ImDrawList* draw_list = viewport->BgFgDrawLists[drawlist_no];
4565
0
    if (draw_list == NULL)
4566
0
    {
4567
0
        draw_list = IM_NEW(ImDrawList)(&g.DrawListSharedData);
4568
0
        draw_list->_OwnerName = drawlist_name;
4569
0
        viewport->BgFgDrawLists[drawlist_no] = draw_list;
4570
0
    }
4571
4572
    // Our ImDrawList system requires that there is always a command
4573
0
    if (viewport->BgFgDrawListsLastFrame[drawlist_no] != g.FrameCount)
4574
0
    {
4575
0
        draw_list->_ResetForNewFrame();
4576
0
        draw_list->PushTextureID(g.IO.Fonts->TexID);
4577
0
        draw_list->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size, false);
4578
0
        viewport->BgFgDrawListsLastFrame[drawlist_no] = g.FrameCount;
4579
0
    }
4580
0
    return draw_list;
4581
0
}
4582
4583
ImDrawList* ImGui::GetBackgroundDrawList(ImGuiViewport* viewport)
4584
0
{
4585
0
    if (viewport == NULL)
4586
0
        viewport = GImGui->CurrentWindow->Viewport;
4587
0
    return GetViewportBgFgDrawList((ImGuiViewportP*)viewport, 0, "##Background");
4588
0
}
4589
4590
ImDrawList* ImGui::GetForegroundDrawList(ImGuiViewport* viewport)
4591
0
{
4592
0
    if (viewport == NULL)
4593
0
        viewport = GImGui->CurrentWindow->Viewport;
4594
0
    return GetViewportBgFgDrawList((ImGuiViewportP*)viewport, 1, "##Foreground");
4595
0
}
4596
4597
ImDrawListSharedData* ImGui::GetDrawListSharedData()
4598
0
{
4599
0
    return &GImGui->DrawListSharedData;
4600
0
}
4601
4602
void ImGui::StartMouseMovingWindow(ImGuiWindow* window)
4603
1
{
4604
    // Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows.
4605
    // We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward.
4606
    // This is because we want ActiveId to be set even when the window is not permitted to move.
4607
1
    ImGuiContext& g = *GImGui;
4608
1
    FocusWindow(window);
4609
1
    SetActiveID(window->MoveId, window);
4610
1
    g.NavDisableHighlight = true;
4611
1
    g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window->RootWindowDockTree->Pos;
4612
1
    g.ActiveIdNoClearOnFocusLoss = true;
4613
1
    SetActiveIdUsingAllKeyboardKeys();
4614
4615
1
    bool can_move_window = true;
4616
1
    if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoMove))
4617
0
        can_move_window = false;
4618
1
    if (ImGuiDockNode* node = window->DockNodeAsHost)
4619
0
        if (node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove))
4620
0
            can_move_window = false;
4621
1
    if (can_move_window)
4622
1
        g.MovingWindow = window;
4623
1
}
4624
4625
// We use 'undock == false' when dragging from title bar to allow moving groups of floating nodes without undocking them.
4626
void ImGui::StartMouseMovingWindowOrNode(ImGuiWindow* window, ImGuiDockNode* node, bool undock)
4627
0
{
4628
0
    ImGuiContext& g = *GImGui;
4629
0
    bool can_undock_node = false;
4630
0
    if (undock && node != NULL && node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove) == 0 && (node->MergedFlags & ImGuiDockNodeFlags_NoUndocking) == 0)
4631
0
    {
4632
        // Can undock if:
4633
        // - part of a hierarchy with more than one visible node (if only one is visible, we'll just move the root window)
4634
        // - part of a dockspace node hierarchy: so we can undock the last single visible node too (trivia: undocking from a fixed/central node will create a new node and copy windows)
4635
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
4636
0
        if (root_node->OnlyNodeWithWindows != node || root_node->CentralNode != NULL)   // -V1051 PVS-Studio thinks node should be root_node and is wrong about that.
4637
0
            can_undock_node = true;
4638
0
    }
4639
4640
0
    const bool clicked = IsMouseClicked(0);
4641
0
    const bool dragging = IsMouseDragging(0);
4642
0
    if (can_undock_node && dragging)
4643
0
        DockContextQueueUndockNode(&g, node); // Will lead to DockNodeStartMouseMovingWindow() -> StartMouseMovingWindow() being called next frame
4644
0
    else if (!can_undock_node && (clicked || dragging) && g.MovingWindow != window)
4645
0
        StartMouseMovingWindow(window);
4646
0
}
4647
4648
// Handle mouse moving window
4649
// Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing()
4650
// FIXME: We don't have strong guarantee that g.MovingWindow stay synched with g.ActiveId == g.MovingWindow->MoveId.
4651
// This is currently enforced by the fact that BeginDragDropSource() is setting all g.ActiveIdUsingXXXX flags to inhibit navigation inputs,
4652
// but if we should more thoroughly test cases where g.ActiveId or g.MovingWindow gets changed and not the other.
4653
void ImGui::UpdateMouseMovingWindowNewFrame()
4654
84.9k
{
4655
84.9k
    ImGuiContext& g = *GImGui;
4656
84.9k
    if (g.MovingWindow != NULL)
4657
1
    {
4658
        // We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window).
4659
        // We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency.
4660
1
        KeepAliveID(g.ActiveId);
4661
1
        IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindowDockTree);
4662
1
        ImGuiWindow* moving_window = g.MovingWindow->RootWindowDockTree;
4663
4664
        // When a window stop being submitted while being dragged, it may will its viewport until next Begin()
4665
1
        const bool window_disappared = (!moving_window->WasActive && !moving_window->Active);
4666
1
        if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos) && !window_disappared)
4667
0
        {
4668
0
            ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
4669
0
            if (moving_window->Pos.x != pos.x || moving_window->Pos.y != pos.y)
4670
0
            {
4671
0
                SetWindowPos(moving_window, pos, ImGuiCond_Always);
4672
0
                if (moving_window->Viewport && moving_window->ViewportOwned) // Synchronize viewport immediately because some overlays may relies on clipping rectangle before we Begin() into the window.
4673
0
                {
4674
0
                    moving_window->Viewport->Pos = pos;
4675
0
                    moving_window->Viewport->UpdateWorkRect();
4676
0
                }
4677
0
            }
4678
0
            FocusWindow(g.MovingWindow);
4679
0
        }
4680
1
        else
4681
1
        {
4682
1
            if (!window_disappared)
4683
1
            {
4684
                // Try to merge the window back into the main viewport.
4685
                // This works because MouseViewport should be != MovingWindow->Viewport on release (as per code in UpdateViewports)
4686
1
                if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
4687
0
                    UpdateTryMergeWindowIntoHostViewport(moving_window, g.MouseViewport);
4688
4689
                // Restore the mouse viewport so that we don't hover the viewport _under_ the moved window during the frame we released the mouse button.
4690
1
                if (moving_window->Viewport && !IsDragDropPayloadBeingAccepted())
4691
1
                    g.MouseViewport = moving_window->Viewport;
4692
4693
                // Clear the NoInput window flag set by the Viewport system
4694
1
                if (moving_window->Viewport)
4695
1
                    moving_window->Viewport->Flags &= ~ImGuiViewportFlags_NoInputs;
4696
1
            }
4697
4698
1
            g.MovingWindow = NULL;
4699
1
            ClearActiveID();
4700
1
        }
4701
1
    }
4702
84.9k
    else
4703
84.9k
    {
4704
        // When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others.
4705
84.9k
        if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId)
4706
0
        {
4707
0
            KeepAliveID(g.ActiveId);
4708
0
            if (!g.IO.MouseDown[0])
4709
0
                ClearActiveID();
4710
0
        }
4711
84.9k
    }
4712
84.9k
}
4713
4714
// Initiate moving window when clicking on empty space or title bar.
4715
// Handle left-click and right-click focus.
4716
void ImGui::UpdateMouseMovingWindowEndFrame()
4717
84.9k
{
4718
84.9k
    ImGuiContext& g = *GImGui;
4719
84.9k
    if (g.ActiveId != 0 || g.HoveredId != 0)
4720
191
        return;
4721
4722
    // Unless we just made a window/popup appear
4723
84.7k
    if (g.NavWindow && g.NavWindow->Appearing)
4724
1
        return;
4725
4726
    // Click on empty space to focus window and start moving
4727
    // (after we're done with all our widgets, so e.g. clicking on docking tab-bar which have set HoveredId already and not get us here!)
4728
84.7k
    if (g.IO.MouseClicked[0])
4729
1.50k
    {
4730
        // Handle the edge case of a popup being closed while clicking in its empty space.
4731
        // If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more.
4732
1.50k
        ImGuiWindow* root_window = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL;
4733
1.50k
        const bool is_closed_popup = root_window && (root_window->Flags & ImGuiWindowFlags_Popup) && !IsPopupOpen(root_window->PopupId, ImGuiPopupFlags_AnyPopupLevel);
4734
4735
1.50k
        if (root_window != NULL && !is_closed_popup)
4736
1
        {
4737
1
            StartMouseMovingWindow(g.HoveredWindow); //-V595
4738
4739
            // Cancel moving if clicked outside of title bar
4740
1
            if (g.IO.ConfigWindowsMoveFromTitleBarOnly)
4741
0
                if (!(root_window->Flags & ImGuiWindowFlags_NoTitleBar) || root_window->DockIsActive)
4742
0
                    if (!root_window->TitleBarRect().Contains(g.IO.MouseClickedPos[0]))
4743
0
                        g.MovingWindow = NULL;
4744
4745
            // Cancel moving if clicked over an item which was disabled or inhibited by popups (note that we know HoveredId == 0 already)
4746
1
            if (g.HoveredIdIsDisabled)
4747
0
                g.MovingWindow = NULL;
4748
1
        }
4749
1.50k
        else if (root_window == NULL && g.NavWindow != NULL)
4750
28
        {
4751
            // Clicking on void disable focus
4752
28
            FocusWindow(NULL, ImGuiFocusRequestFlags_UnlessBelowModal);
4753
28
        }
4754
1.50k
    }
4755
4756
    // With right mouse button we close popups without changing focus based on where the mouse is aimed
4757
    // Instead, focus will be restored to the window under the bottom-most closed popup.
4758
    // (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger)
4759
84.7k
    if (g.IO.MouseClicked[1])
4760
50
    {
4761
        // Find the top-most window between HoveredWindow and the top-most Modal Window.
4762
        // This is where we can trim the popup stack.
4763
50
        ImGuiWindow* modal = GetTopMostPopupModal();
4764
50
        bool hovered_window_above_modal = g.HoveredWindow && (modal == NULL || IsWindowAbove(g.HoveredWindow, modal));
4765
50
        ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal, true);
4766
50
    }
4767
84.7k
}
4768
4769
// This is called during NewFrame()->UpdateViewportsNewFrame() only.
4770
// Need to keep in sync with SetWindowPos()
4771
static void TranslateWindow(ImGuiWindow* window, const ImVec2& delta)
4772
0
{
4773
0
    window->Pos += delta;
4774
0
    window->ClipRect.Translate(delta);
4775
0
    window->OuterRectClipped.Translate(delta);
4776
0
    window->InnerRect.Translate(delta);
4777
0
    window->DC.CursorPos += delta;
4778
0
    window->DC.CursorStartPos += delta;
4779
0
    window->DC.CursorMaxPos += delta;
4780
0
    window->DC.IdealMaxPos += delta;
4781
0
}
4782
4783
static void ScaleWindow(ImGuiWindow* window, float scale)
4784
0
{
4785
0
    ImVec2 origin = window->Viewport->Pos;
4786
0
    window->Pos = ImFloor((window->Pos - origin) * scale + origin);
4787
0
    window->Size = ImTrunc(window->Size * scale);
4788
0
    window->SizeFull = ImTrunc(window->SizeFull * scale);
4789
0
    window->ContentSize = ImTrunc(window->ContentSize * scale);
4790
0
}
4791
4792
static bool IsWindowActiveAndVisible(ImGuiWindow* window)
4793
278k
{
4794
278k
    return (window->Active) && (!window->Hidden);
4795
278k
}
4796
4797
// The reason this is exposed in imgui_internal.h is: on touch-based system that don't have hovering, we want to dispatch inputs to the right target (imgui vs imgui+app)
4798
void ImGui::UpdateHoveredWindowAndCaptureFlags()
4799
84.9k
{
4800
84.9k
    ImGuiContext& g = *GImGui;
4801
84.9k
    ImGuiIO& io = g.IO;
4802
4803
    // FIXME-DPI: This storage was added on 2021/03/31 for test engine, but if we want to multiply WINDOWS_HOVER_PADDING
4804
    // by DpiScale, we need to make this window-agnostic anyhow, maybe need storing inside ImGuiWindow.
4805
84.9k
    g.WindowsHoverPadding = ImMax(g.Style.TouchExtraPadding, ImVec2(WINDOWS_HOVER_PADDING, WINDOWS_HOVER_PADDING));
4806
4807
    // Find the window hovered by mouse:
4808
    // - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow.
4809
    // - When moving a window we can skip the search, which also conveniently bypasses the fact that window->WindowRectClipped is lagging as this point of the frame.
4810
    // - We also support the moved window toggling the NoInputs flag after moving has started in order to be able to detect windows below it, which is useful for e.g. docking mechanisms.
4811
84.9k
    bool clear_hovered_windows = false;
4812
84.9k
    FindHoveredWindowEx(g.IO.MousePos, false, &g.HoveredWindow, &g.HoveredWindowUnderMovingWindow);
4813
84.9k
    IM_ASSERT(g.HoveredWindow == NULL || g.HoveredWindow == g.MovingWindow || g.HoveredWindow->Viewport == g.MouseViewport);
4814
84.9k
    g.HoveredWindowBeforeClear = g.HoveredWindow;
4815
4816
    // Modal windows prevents mouse from hovering behind them.
4817
84.9k
    ImGuiWindow* modal_window = GetTopMostPopupModal();
4818
84.9k
    if (modal_window && g.HoveredWindow && !IsWindowWithinBeginStackOf(g.HoveredWindow->RootWindow, modal_window)) // FIXME-MERGE: RootWindowDockTree ?
4819
0
        clear_hovered_windows = true;
4820
4821
    // Disabled mouse hovering (we don't currently clear MousePos, we could)
4822
84.9k
    if (io.ConfigFlags & ImGuiConfigFlags_NoMouse)
4823
0
        clear_hovered_windows = true;
4824
4825
    // We track click ownership. When clicked outside of a window the click is owned by the application and
4826
    // won't report hovering nor request capture even while dragging over our windows afterward.
4827
84.9k
    const bool has_open_popup = (g.OpenPopupStack.Size > 0);
4828
84.9k
    const bool has_open_modal = (modal_window != NULL);
4829
84.9k
    int mouse_earliest_down = -1;
4830
84.9k
    bool mouse_any_down = false;
4831
509k
    for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
4832
424k
    {
4833
424k
        if (io.MouseClicked[i])
4834
4.14k
        {
4835
4.14k
            io.MouseDownOwned[i] = (g.HoveredWindow != NULL) || has_open_popup;
4836
4.14k
            io.MouseDownOwnedUnlessPopupClose[i] = (g.HoveredWindow != NULL) || has_open_modal;
4837
4.14k
        }
4838
424k
        mouse_any_down |= io.MouseDown[i];
4839
424k
        if (io.MouseDown[i] || io.MouseReleased[i]) // Increase release frame for our evaluation of earliest button (#1392)
4840
159k
            if (mouse_earliest_down == -1 || io.MouseClickedTime[i] < io.MouseClickedTime[mouse_earliest_down])
4841
98.7k
                mouse_earliest_down = i;
4842
424k
    }
4843
84.9k
    const bool mouse_avail = (mouse_earliest_down == -1) || io.MouseDownOwned[mouse_earliest_down];
4844
84.9k
    const bool mouse_avail_unless_popup_close = (mouse_earliest_down == -1) || io.MouseDownOwnedUnlessPopupClose[mouse_earliest_down];
4845
4846
    // If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
4847
    // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)
4848
84.9k
    const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;
4849
84.9k
    if (!mouse_avail && !mouse_dragging_extern_payload)
4850
62.2k
        clear_hovered_windows = true;
4851
4852
84.9k
    if (clear_hovered_windows)
4853
62.2k
        g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
4854
4855
    // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to Dear ImGui only, false = dispatch mouse to Dear ImGui + underlying app)
4856
    // Update io.WantCaptureMouseAllowPopupClose (experimental) to give a chance for app to react to popup closure with a drag
4857
84.9k
    if (g.WantCaptureMouseNextFrame != -1)
4858
0
    {
4859
0
        io.WantCaptureMouse = io.WantCaptureMouseUnlessPopupClose = (g.WantCaptureMouseNextFrame != 0);
4860
0
    }
4861
84.9k
    else
4862
84.9k
    {
4863
84.9k
        io.WantCaptureMouse = (mouse_avail && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_popup;
4864
84.9k
        io.WantCaptureMouseUnlessPopupClose = (mouse_avail_unless_popup_close && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_modal;
4865
84.9k
    }
4866
4867
    // Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to Dear ImGui only, false = dispatch keyboard info to Dear ImGui + underlying app)
4868
84.9k
    io.WantCaptureKeyboard = (g.ActiveId != 0) || (modal_window != NULL);
4869
84.9k
    if (io.NavActive && (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && !(io.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard))
4870
13.5k
        io.WantCaptureKeyboard = true;
4871
84.9k
    if (g.WantCaptureKeyboardNextFrame != -1) // Manual override
4872
0
        io.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);
4873
4874
    // Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible
4875
84.9k
    io.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false;
4876
84.9k
}
4877
4878
// Calling SetupDrawListSharedData() is followed by SetCurrentFont() which sets up the remaining data.
4879
static void SetupDrawListSharedData()
4880
84.9k
{
4881
84.9k
    ImGuiContext& g = *GImGui;
4882
84.9k
    ImRect virtual_space(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
4883
84.9k
    for (ImGuiViewportP* viewport : g.Viewports)
4884
84.9k
        virtual_space.Add(viewport->GetMainRect());
4885
84.9k
    g.DrawListSharedData.ClipRectFullscreen = virtual_space.ToVec4();
4886
84.9k
    g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
4887
84.9k
    g.DrawListSharedData.SetCircleTessellationMaxError(g.Style.CircleTessellationMaxError);
4888
84.9k
    g.DrawListSharedData.InitialFlags = ImDrawListFlags_None;
4889
84.9k
    if (g.Style.AntiAliasedLines)
4890
84.9k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines;
4891
84.9k
    if (g.Style.AntiAliasedLinesUseTex && !(g.IO.Fonts->Flags & ImFontAtlasFlags_NoBakedLines))
4892
84.9k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTex;
4893
84.9k
    if (g.Style.AntiAliasedFill)
4894
84.9k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill;
4895
84.9k
    if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset)
4896
0
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset;
4897
84.9k
}
4898
4899
void ImGui::NewFrame()
4900
84.9k
{
4901
84.9k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
4902
84.9k
    ImGuiContext& g = *GImGui;
4903
4904
    // Remove pending delete hooks before frame start.
4905
    // This deferred removal avoid issues of removal while iterating the hook vector
4906
84.9k
    for (int n = g.Hooks.Size - 1; n >= 0; n--)
4907
0
        if (g.Hooks[n].Type == ImGuiContextHookType_PendingRemoval_)
4908
0
            g.Hooks.erase(&g.Hooks[n]);
4909
4910
84.9k
    CallContextHooks(&g, ImGuiContextHookType_NewFramePre);
4911
4912
    // Check and assert for various common IO and Configuration mistakes
4913
84.9k
    g.ConfigFlagsLastFrame = g.ConfigFlagsCurrFrame;
4914
84.9k
    ErrorCheckNewFrameSanityChecks();
4915
84.9k
    g.ConfigFlagsCurrFrame = g.IO.ConfigFlags;
4916
4917
    // Load settings on first frame, save settings when modified (after a delay)
4918
84.9k
    UpdateSettings();
4919
4920
84.9k
    g.Time += g.IO.DeltaTime;
4921
84.9k
    g.WithinFrameScope = true;
4922
84.9k
    g.FrameCount += 1;
4923
84.9k
    g.TooltipOverrideCount = 0;
4924
84.9k
    g.WindowsActiveCount = 0;
4925
84.9k
    g.MenusIdSubmittedThisFrame.resize(0);
4926
4927
    // Calculate frame-rate for the user, as a purely luxurious feature
4928
84.9k
    g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
4929
84.9k
    g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
4930
84.9k
    g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
4931
84.9k
    g.FramerateSecPerFrameCount = ImMin(g.FramerateSecPerFrameCount + 1, IM_ARRAYSIZE(g.FramerateSecPerFrame));
4932
84.9k
    g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)g.FramerateSecPerFrameCount)) : FLT_MAX;
4933
4934
    // Process input queue (trickle as many events as possible), turn events into writes to IO structure
4935
84.9k
    g.InputEventsTrail.resize(0);
4936
84.9k
    UpdateInputEvents(g.IO.ConfigInputTrickleEventQueue);
4937
4938
    // Update viewports (after processing input queue, so io.MouseHoveredViewport is set)
4939
84.9k
    UpdateViewportsNewFrame();
4940
4941
    // Setup current font and draw list shared data
4942
    // FIXME-VIEWPORT: the concept of a single ClipRectFullscreen is not ideal!
4943
84.9k
    g.IO.Fonts->Locked = true;
4944
84.9k
    SetupDrawListSharedData();
4945
84.9k
    SetCurrentFont(GetDefaultFont());
4946
84.9k
    IM_ASSERT(g.Font->IsLoaded());
4947
4948
    // Mark rendering data as invalid to prevent user who may have a handle on it to use it.
4949
84.9k
    for (ImGuiViewportP* viewport : g.Viewports)
4950
84.9k
    {
4951
84.9k
        viewport->DrawData = NULL;
4952
84.9k
        viewport->DrawDataP.Valid = false;
4953
84.9k
    }
4954
4955
    // Drag and drop keep the source ID alive so even if the source disappear our state is consistent
4956
84.9k
    if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId)
4957
0
        KeepAliveID(g.DragDropPayload.SourceId);
4958
4959
    // Update HoveredId data
4960
84.9k
    if (!g.HoveredIdPreviousFrame)
4961
84.8k
        g.HoveredIdTimer = 0.0f;
4962
84.9k
    if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId))
4963
84.8k
        g.HoveredIdNotActiveTimer = 0.0f;
4964
84.9k
    if (g.HoveredId)
4965
163
        g.HoveredIdTimer += g.IO.DeltaTime;
4966
84.9k
    if (g.HoveredId && g.ActiveId != g.HoveredId)
4967
163
        g.HoveredIdNotActiveTimer += g.IO.DeltaTime;
4968
84.9k
    g.HoveredIdPreviousFrame = g.HoveredId;
4969
84.9k
    g.HoveredId = 0;
4970
84.9k
    g.HoveredIdAllowOverlap = false;
4971
84.9k
    g.HoveredIdIsDisabled = false;
4972
4973
    // Clear ActiveID if the item is not alive anymore.
4974
    // In 1.87, the common most call to KeepAliveID() was moved from GetID() to ItemAdd().
4975
    // As a result, custom widget using ButtonBehavior() _without_ ItemAdd() need to call KeepAliveID() themselves.
4976
84.9k
    if (g.ActiveId != 0 && g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId)
4977
0
    {
4978
0
        IMGUI_DEBUG_LOG_ACTIVEID("NewFrame(): ClearActiveID() because it isn't marked alive anymore!\n");
4979
0
        ClearActiveID();
4980
0
    }
4981
4982
    // Update ActiveId data (clear reference to active widget if the widget isn't alive anymore)
4983
84.9k
    if (g.ActiveId)
4984
21
        g.ActiveIdTimer += g.IO.DeltaTime;
4985
84.9k
    g.LastActiveIdTimer += g.IO.DeltaTime;
4986
84.9k
    g.ActiveIdPreviousFrame = g.ActiveId;
4987
84.9k
    g.ActiveIdPreviousFrameWindow = g.ActiveIdWindow;
4988
84.9k
    g.ActiveIdPreviousFrameHasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore;
4989
84.9k
    g.ActiveIdIsAlive = 0;
4990
84.9k
    g.ActiveIdHasBeenEditedThisFrame = false;
4991
84.9k
    g.ActiveIdPreviousFrameIsAlive = false;
4992
84.9k
    g.ActiveIdIsJustActivated = false;
4993
84.9k
    if (g.TempInputId != 0 && g.ActiveId != g.TempInputId)
4994
0
        g.TempInputId = 0;
4995
84.9k
    if (g.ActiveId == 0)
4996
84.9k
    {
4997
84.9k
        g.ActiveIdUsingNavDirMask = 0x00;
4998
84.9k
        g.ActiveIdUsingAllKeyboardKeys = false;
4999
84.9k
    }
5000
5001
    // Record when we have been stationary as this state is preserved while over same item.
5002
    // FIXME: The way this is expressed means user cannot alter HoverStationaryDelay during the frame to use varying values.
5003
    // To allow this we should store HoverItemMaxStationaryTime+ID and perform the >= check in IsItemHovered() function.
5004
84.9k
    if (g.HoverItemDelayId != 0 && g.MouseStationaryTimer >= g.Style.HoverStationaryDelay)
5005
0
        g.HoverItemUnlockedStationaryId = g.HoverItemDelayId;
5006
84.9k
    else if (g.HoverItemDelayId == 0)
5007
84.9k
        g.HoverItemUnlockedStationaryId = 0;
5008
84.9k
    if (g.HoveredWindow != NULL && g.MouseStationaryTimer >= g.Style.HoverStationaryDelay)
5009
218
        g.HoverWindowUnlockedStationaryId = g.HoveredWindow->ID;
5010
84.7k
    else if (g.HoveredWindow == NULL)
5011
84.6k
        g.HoverWindowUnlockedStationaryId = 0;
5012
5013
    // Update hover delay for IsItemHovered() with delays and tooltips
5014
84.9k
    g.HoverItemDelayIdPreviousFrame = g.HoverItemDelayId;
5015
84.9k
    if (g.HoverItemDelayId != 0)
5016
0
    {
5017
0
        g.HoverItemDelayTimer += g.IO.DeltaTime;
5018
0
        g.HoverItemDelayClearTimer = 0.0f;
5019
0
        g.HoverItemDelayId = 0;
5020
0
    }
5021
84.9k
    else if (g.HoverItemDelayTimer > 0.0f)
5022
0
    {
5023
        // This gives a little bit of leeway before clearing the hover timer, allowing mouse to cross gaps
5024
        // We could expose 0.25f as style.HoverClearDelay but I am not sure of the logic yet, this is particularly subtle.
5025
0
        g.HoverItemDelayClearTimer += g.IO.DeltaTime;
5026
0
        if (g.HoverItemDelayClearTimer >= ImMax(0.25f, g.IO.DeltaTime * 2.0f)) // ~7 frames at 30 Hz + allow for low framerate
5027
0
            g.HoverItemDelayTimer = g.HoverItemDelayClearTimer = 0.0f; // May want a decaying timer, in which case need to clamp at max first, based on max of caller last requested timer.
5028
0
    }
5029
5030
    // Drag and drop
5031
84.9k
    g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
5032
84.9k
    g.DragDropAcceptIdCurr = 0;
5033
84.9k
    g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
5034
84.9k
    g.DragDropWithinSource = false;
5035
84.9k
    g.DragDropWithinTarget = false;
5036
84.9k
    g.DragDropHoldJustPressedId = 0;
5037
5038
    // Close popups on focus lost (currently wip/opt-in)
5039
    //if (g.IO.AppFocusLost)
5040
    //    ClosePopupsExceptModals();
5041
5042
    // Update keyboard input state
5043
84.9k
    UpdateKeyboardInputs();
5044
5045
    //IM_ASSERT(g.IO.KeyCtrl == IsKeyDown(ImGuiKey_LeftCtrl) || IsKeyDown(ImGuiKey_RightCtrl));
5046
    //IM_ASSERT(g.IO.KeyShift == IsKeyDown(ImGuiKey_LeftShift) || IsKeyDown(ImGuiKey_RightShift));
5047
    //IM_ASSERT(g.IO.KeyAlt == IsKeyDown(ImGuiKey_LeftAlt) || IsKeyDown(ImGuiKey_RightAlt));
5048
    //IM_ASSERT(g.IO.KeySuper == IsKeyDown(ImGuiKey_LeftSuper) || IsKeyDown(ImGuiKey_RightSuper));
5049
5050
    // Update gamepad/keyboard navigation
5051
84.9k
    NavUpdate();
5052
5053
    // Update mouse input state
5054
84.9k
    UpdateMouseInputs();
5055
5056
    // Undocking
5057
    // (needs to be before UpdateMouseMovingWindowNewFrame so the window is already offset and following the mouse on the detaching frame)
5058
84.9k
    DockContextNewFrameUpdateUndocking(&g);
5059
5060
    // Find hovered window
5061
    // (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame)
5062
84.9k
    UpdateHoveredWindowAndCaptureFlags();
5063
5064
    // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
5065
84.9k
    UpdateMouseMovingWindowNewFrame();
5066
5067
    // Background darkening/whitening
5068
84.9k
    if (GetTopMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f))
5069
0
        g.DimBgRatio = ImMin(g.DimBgRatio + g.IO.DeltaTime * 6.0f, 1.0f);
5070
84.9k
    else
5071
84.9k
        g.DimBgRatio = ImMax(g.DimBgRatio - g.IO.DeltaTime * 10.0f, 0.0f);
5072
5073
84.9k
    g.MouseCursor = ImGuiMouseCursor_Arrow;
5074
84.9k
    g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;
5075
5076
    // Platform IME data: reset for the frame
5077
84.9k
    g.PlatformImeDataPrev = g.PlatformImeData;
5078
84.9k
    g.PlatformImeData.WantVisible = false;
5079
5080
    // Mouse wheel scrolling, scale
5081
84.9k
    UpdateMouseWheel();
5082
5083
    // Mark all windows as not visible and compact unused memory.
5084
84.9k
    IM_ASSERT(g.WindowsFocusOrder.Size <= g.Windows.Size);
5085
84.9k
    const float memory_compact_start_time = (g.GcCompactAll || g.IO.ConfigMemoryCompactTimer < 0.0f) ? FLT_MAX : (float)g.Time - g.IO.ConfigMemoryCompactTimer;
5086
84.9k
    for (ImGuiWindow* window : g.Windows)
5087
254k
    {
5088
254k
        window->WasActive = window->Active;
5089
254k
        window->Active = false;
5090
254k
        window->WriteAccessed = false;
5091
254k
        window->BeginCountPreviousFrame = window->BeginCount;
5092
254k
        window->BeginCount = 0;
5093
5094
        // Garbage collect transient buffers of recently unused windows
5095
254k
        if (!window->WasActive && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time)
5096
1
            GcCompactTransientWindowBuffers(window);
5097
254k
    }
5098
5099
    // Garbage collect transient buffers of recently unused tables
5100
84.9k
    for (int i = 0; i < g.TablesLastTimeActive.Size; i++)
5101
0
        if (g.TablesLastTimeActive[i] >= 0.0f && g.TablesLastTimeActive[i] < memory_compact_start_time)
5102
0
            TableGcCompactTransientBuffers(g.Tables.GetByIndex(i));
5103
84.9k
    for (ImGuiTableTempData& table_temp_data : g.TablesTempData)
5104
0
        if (table_temp_data.LastTimeActive >= 0.0f && table_temp_data.LastTimeActive < memory_compact_start_time)
5105
0
            TableGcCompactTransientBuffers(&table_temp_data);
5106
84.9k
    if (g.GcCompactAll)
5107
0
        GcCompactTransientMiscBuffers();
5108
84.9k
    g.GcCompactAll = false;
5109
5110
    // Closing the focused window restore focus to the first active root window in descending z-order
5111
84.9k
    if (g.NavWindow && !g.NavWindow->WasActive)
5112
0
        FocusTopMostWindowUnderOne(NULL, NULL, NULL, ImGuiFocusRequestFlags_RestoreFocusedChild);
5113
5114
    // No window should be open at the beginning of the frame.
5115
    // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
5116
84.9k
    g.CurrentWindowStack.resize(0);
5117
84.9k
    g.BeginPopupStack.resize(0);
5118
84.9k
    g.ItemFlagsStack.resize(0);
5119
84.9k
    g.ItemFlagsStack.push_back(ImGuiItemFlags_AutoClosePopups); // Default flags
5120
84.9k
    g.CurrentItemFlags = g.ItemFlagsStack.back();
5121
84.9k
    g.GroupStack.resize(0);
5122
5123
    // Docking
5124
84.9k
    DockContextNewFrameUpdateDocking(&g);
5125
5126
    // [DEBUG] Update debug features
5127
84.9k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
5128
84.9k
    UpdateDebugToolItemPicker();
5129
84.9k
    UpdateDebugToolStackQueries();
5130
84.9k
    UpdateDebugToolFlashStyleColor();
5131
84.9k
    if (g.DebugLocateFrames > 0 && --g.DebugLocateFrames == 0)
5132
0
    {
5133
0
        g.DebugLocateId = 0;
5134
0
        g.DebugBreakInLocateId = false;
5135
0
    }
5136
84.9k
    if (g.DebugLogAutoDisableFrames > 0 && --g.DebugLogAutoDisableFrames == 0)
5137
0
    {
5138
0
        DebugLog("(Debug Log: Auto-disabled some ImGuiDebugLogFlags after 2 frames)\n");
5139
0
        g.DebugLogFlags &= ~g.DebugLogAutoDisableFlags;
5140
0
        g.DebugLogAutoDisableFlags = ImGuiDebugLogFlags_None;
5141
0
    }
5142
84.9k
#endif
5143
5144
    // Create implicit/fallback window - which we will only render it if the user has added something to it.
5145
    // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags.
5146
    // This fallback is particularly important as it prevents ImGui:: calls from crashing.
5147
84.9k
    g.WithinFrameScopeWithImplicitWindow = true;
5148
84.9k
    SetNextWindowSize(ImVec2(400, 400), ImGuiCond_FirstUseEver);
5149
84.9k
    Begin("Debug##Default");
5150
84.9k
    IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true);
5151
5152
    // [DEBUG] When io.ConfigDebugBeginReturnValue is set, we make Begin()/BeginChild() return false at different level of the window-stack,
5153
    // allowing to validate correct Begin/End behavior in user code.
5154
84.9k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
5155
84.9k
    if (g.IO.ConfigDebugBeginReturnValueLoop)
5156
0
        g.DebugBeginReturnValueCullDepth = (g.DebugBeginReturnValueCullDepth == -1) ? 0 : ((g.DebugBeginReturnValueCullDepth + ((g.FrameCount % 4) == 0 ? 1 : 0)) % 10);
5157
84.9k
    else
5158
84.9k
        g.DebugBeginReturnValueCullDepth = -1;
5159
84.9k
#endif
5160
5161
84.9k
    CallContextHooks(&g, ImGuiContextHookType_NewFramePost);
5162
84.9k
}
5163
5164
// FIXME: Add a more explicit sort order in the window structure.
5165
static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs)
5166
0
{
5167
0
    const ImGuiWindow* const a = *(const ImGuiWindow* const *)lhs;
5168
0
    const ImGuiWindow* const b = *(const ImGuiWindow* const *)rhs;
5169
0
    if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))
5170
0
        return d;
5171
0
    if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
5172
0
        return d;
5173
0
    return (a->BeginOrderWithinParent - b->BeginOrderWithinParent);
5174
0
}
5175
5176
static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window)
5177
254k
{
5178
254k
    out_sorted_windows->push_back(window);
5179
254k
    if (window->Active)
5180
108k
    {
5181
108k
        int count = window->DC.ChildWindows.Size;
5182
108k
        ImQsort(window->DC.ChildWindows.Data, (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer);
5183
132k
        for (int i = 0; i < count; i++)
5184
23.7k
        {
5185
23.7k
            ImGuiWindow* child = window->DC.ChildWindows[i];
5186
23.7k
            if (child->Active)
5187
23.7k
                AddWindowToSortBuffer(out_sorted_windows, child);
5188
23.7k
        }
5189
108k
    }
5190
254k
}
5191
5192
static void AddWindowToDrawData(ImGuiWindow* window, int layer)
5193
108k
{
5194
108k
    ImGuiContext& g = *GImGui;
5195
108k
    ImGuiViewportP* viewport = window->Viewport;
5196
108k
    IM_ASSERT(viewport != NULL);
5197
108k
    g.IO.MetricsRenderWindows++;
5198
108k
    if (window->DrawList->_Splitter._Count > 1)
5199
0
        window->DrawList->ChannelsMerge(); // Merge if user forgot to merge back. Also required in Docking branch for ImGuiWindowFlags_DockNodeHost windows.
5200
108k
    ImGui::AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[layer], window->DrawList);
5201
108k
    for (ImGuiWindow* child : window->DC.ChildWindows)
5202
23.7k
        if (IsWindowActiveAndVisible(child)) // Clipped children may have been marked not active
5203
23.7k
            AddWindowToDrawData(child, layer);
5204
108k
}
5205
5206
static inline int GetWindowDisplayLayer(ImGuiWindow* window)
5207
84.9k
{
5208
84.9k
    return (window->Flags & ImGuiWindowFlags_Tooltip) ? 1 : 0;
5209
84.9k
}
5210
5211
// Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu)
5212
static inline void AddRootWindowToDrawData(ImGuiWindow* window)
5213
84.9k
{
5214
84.9k
    AddWindowToDrawData(window, GetWindowDisplayLayer(window));
5215
84.9k
}
5216
5217
static void FlattenDrawDataIntoSingleLayer(ImDrawDataBuilder* builder)
5218
84.9k
{
5219
84.9k
    int n = builder->Layers[0]->Size;
5220
84.9k
    int full_size = n;
5221
169k
    for (int i = 1; i < IM_ARRAYSIZE(builder->Layers); i++)
5222
84.9k
        full_size += builder->Layers[i]->Size;
5223
84.9k
    builder->Layers[0]->resize(full_size);
5224
169k
    for (int layer_n = 1; layer_n < IM_ARRAYSIZE(builder->Layers); layer_n++)
5225
84.9k
    {
5226
84.9k
        ImVector<ImDrawList*>* layer = builder->Layers[layer_n];
5227
84.9k
        if (layer->empty())
5228
84.9k
            continue;
5229
0
        memcpy(builder->Layers[0]->Data + n, layer->Data, layer->Size * sizeof(ImDrawList*));
5230
0
        n += layer->Size;
5231
0
        layer->resize(0);
5232
0
    }
5233
84.9k
}
5234
5235
static void InitViewportDrawData(ImGuiViewportP* viewport)
5236
84.9k
{
5237
84.9k
    ImGuiIO& io = ImGui::GetIO();
5238
84.9k
    ImDrawData* draw_data = &viewport->DrawDataP;
5239
5240
84.9k
    viewport->DrawData = draw_data; // Make publicly accessible
5241
84.9k
    viewport->DrawDataBuilder.Layers[0] = &draw_data->CmdLists;
5242
84.9k
    viewport->DrawDataBuilder.Layers[1] = &viewport->DrawDataBuilder.LayerData1;
5243
84.9k
    viewport->DrawDataBuilder.Layers[0]->resize(0);
5244
84.9k
    viewport->DrawDataBuilder.Layers[1]->resize(0);
5245
5246
    // When minimized, we report draw_data->DisplaySize as zero to be consistent with non-viewport mode,
5247
    // and to allow applications/backends to easily skip rendering.
5248
    // FIXME: Note that we however do NOT attempt to report "zero drawlist / vertices" into the ImDrawData structure.
5249
    // This is because the work has been done already, and its wasted! We should fix that and add optimizations for
5250
    // it earlier in the pipeline, rather than pretend to hide the data at the end of the pipeline.
5251
84.9k
    const bool is_minimized = (viewport->Flags & ImGuiViewportFlags_IsMinimized) != 0;
5252
5253
84.9k
    draw_data->Valid = true;
5254
84.9k
    draw_data->CmdListsCount = 0;
5255
84.9k
    draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0;
5256
84.9k
    draw_data->DisplayPos = viewport->Pos;
5257
84.9k
    draw_data->DisplaySize = is_minimized ? ImVec2(0.0f, 0.0f) : viewport->Size;
5258
84.9k
    draw_data->FramebufferScale = io.DisplayFramebufferScale; // FIXME-VIEWPORT: This may vary on a per-monitor/viewport basis?
5259
84.9k
    draw_data->OwnerViewport = viewport;
5260
84.9k
}
5261
5262
// Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering.
5263
// - When using this function it is sane to ensure that float are perfectly rounded to integer values,
5264
//   so that e.g. (int)(max.x-min.x) in user's render produce correct result.
5265
// - If the code here changes, may need to update code of functions like NextColumn() and PushColumnClipRect():
5266
//   some frequently called functions which to modify both channels and clipping simultaneously tend to use the
5267
//   more specialized SetWindowClipRectBeforeSetChannel() to avoid extraneous updates of underlying ImDrawCmds.
5268
void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect)
5269
387k
{
5270
387k
    ImGuiWindow* window = GetCurrentWindow();
5271
387k
    window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
5272
387k
    window->ClipRect = window->DrawList->_ClipRectStack.back();
5273
387k
}
5274
5275
void ImGui::PopClipRect()
5276
193k
{
5277
193k
    ImGuiWindow* window = GetCurrentWindow();
5278
193k
    window->DrawList->PopClipRect();
5279
193k
    window->ClipRect = window->DrawList->_ClipRectStack.back();
5280
193k
}
5281
5282
static ImGuiWindow* FindFrontMostVisibleChildWindow(ImGuiWindow* window)
5283
0
{
5284
0
    for (int n = window->DC.ChildWindows.Size - 1; n >= 0; n--)
5285
0
        if (IsWindowActiveAndVisible(window->DC.ChildWindows[n]))
5286
0
            return FindFrontMostVisibleChildWindow(window->DC.ChildWindows[n]);
5287
0
    return window;
5288
0
}
5289
5290
static void ImGui::RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col)
5291
0
{
5292
0
    if ((col & IM_COL32_A_MASK) == 0)
5293
0
        return;
5294
5295
0
    ImGuiViewportP* viewport = window->Viewport;
5296
0
    ImRect viewport_rect = viewport->GetMainRect();
5297
5298
    // Draw behind window by moving the draw command at the FRONT of the draw list
5299
0
    {
5300
        // Draw list have been trimmed already, hence the explicit recreation of a draw command if missing.
5301
        // FIXME: This is creating complication, might be simpler if we could inject a drawlist in drawdata at a given position and not attempt to manipulate ImDrawCmd order.
5302
0
        ImDrawList* draw_list = window->RootWindowDockTree->DrawList;
5303
0
        draw_list->ChannelsMerge();
5304
0
        if (draw_list->CmdBuffer.Size == 0)
5305
0
            draw_list->AddDrawCmd();
5306
0
        draw_list->PushClipRect(viewport_rect.Min - ImVec2(1, 1), viewport_rect.Max + ImVec2(1, 1), false); // FIXME: Need to stricty ensure ImDrawCmd are not merged (ElemCount==6 checks below will verify that)
5307
0
        draw_list->AddRectFilled(viewport_rect.Min, viewport_rect.Max, col);
5308
0
        ImDrawCmd cmd = draw_list->CmdBuffer.back();
5309
0
        IM_ASSERT(cmd.ElemCount == 6);
5310
0
        draw_list->CmdBuffer.pop_back();
5311
0
        draw_list->CmdBuffer.push_front(cmd);
5312
0
        draw_list->AddDrawCmd(); // We need to create a command as CmdBuffer.back().IdxOffset won't be correct if we append to same command.
5313
0
        draw_list->PopClipRect();
5314
0
    }
5315
5316
    // Draw over sibling docking nodes in a same docking tree
5317
0
    if (window->RootWindow->DockIsActive)
5318
0
    {
5319
0
        ImDrawList* draw_list = FindFrontMostVisibleChildWindow(window->RootWindowDockTree)->DrawList;
5320
0
        draw_list->ChannelsMerge();
5321
0
        if (draw_list->CmdBuffer.Size == 0)
5322
0
            draw_list->AddDrawCmd();
5323
0
        draw_list->PushClipRect(viewport_rect.Min, viewport_rect.Max, false);
5324
0
        RenderRectFilledWithHole(draw_list, window->RootWindowDockTree->Rect(), window->RootWindow->Rect(), col, 0.0f);// window->RootWindowDockTree->WindowRounding);
5325
0
        draw_list->PopClipRect();
5326
0
    }
5327
0
}
5328
5329
ImGuiWindow* ImGui::FindBottomMostVisibleWindowWithinBeginStack(ImGuiWindow* parent_window)
5330
0
{
5331
0
    ImGuiContext& g = *GImGui;
5332
0
    ImGuiWindow* bottom_most_visible_window = parent_window;
5333
0
    for (int i = FindWindowDisplayIndex(parent_window); i >= 0; i--)
5334
0
    {
5335
0
        ImGuiWindow* window = g.Windows[i];
5336
0
        if (window->Flags & ImGuiWindowFlags_ChildWindow)
5337
0
            continue;
5338
0
        if (!IsWindowWithinBeginStackOf(window, parent_window))
5339
0
            break;
5340
0
        if (IsWindowActiveAndVisible(window) && GetWindowDisplayLayer(window) <= GetWindowDisplayLayer(parent_window))
5341
0
            bottom_most_visible_window = window;
5342
0
    }
5343
0
    return bottom_most_visible_window;
5344
0
}
5345
5346
// Important: AddWindowToDrawData() has not been called yet, meaning DockNodeHost windows needs a DrawList->ChannelsMerge() before usage.
5347
// We call ChannelsMerge() lazily here at it is faster that doing a full iteration of g.Windows[] prior to calling RenderDimmedBackgrounds().
5348
static void ImGui::RenderDimmedBackgrounds()
5349
84.9k
{
5350
84.9k
    ImGuiContext& g = *GImGui;
5351
84.9k
    ImGuiWindow* modal_window = GetTopMostAndVisiblePopupModal();
5352
84.9k
    if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
5353
84.9k
        return;
5354
0
    const bool dim_bg_for_modal = (modal_window != NULL);
5355
0
    const bool dim_bg_for_window_list = (g.NavWindowingTargetAnim != NULL && g.NavWindowingTargetAnim->Active);
5356
0
    if (!dim_bg_for_modal && !dim_bg_for_window_list)
5357
0
        return;
5358
5359
0
    ImGuiViewport* viewports_already_dimmed[2] = { NULL, NULL };
5360
0
    if (dim_bg_for_modal)
5361
0
    {
5362
        // Draw dimming behind modal or a begin stack child, whichever comes first in draw order.
5363
0
        ImGuiWindow* dim_behind_window = FindBottomMostVisibleWindowWithinBeginStack(modal_window);
5364
0
        RenderDimmedBackgroundBehindWindow(dim_behind_window, GetColorU32(modal_window->DC.ModalDimBgColor, g.DimBgRatio));
5365
0
        viewports_already_dimmed[0] = modal_window->Viewport;
5366
0
    }
5367
0
    else if (dim_bg_for_window_list)
5368
0
    {
5369
        // Draw dimming behind CTRL+Tab target window and behind CTRL+Tab UI window
5370
0
        RenderDimmedBackgroundBehindWindow(g.NavWindowingTargetAnim, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
5371
0
        if (g.NavWindowingListWindow != NULL && g.NavWindowingListWindow->Viewport && g.NavWindowingListWindow->Viewport != g.NavWindowingTargetAnim->Viewport)
5372
0
            RenderDimmedBackgroundBehindWindow(g.NavWindowingListWindow, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
5373
0
        viewports_already_dimmed[0] = g.NavWindowingTargetAnim->Viewport;
5374
0
        viewports_already_dimmed[1] = g.NavWindowingListWindow ? g.NavWindowingListWindow->Viewport : NULL;
5375
5376
        // Draw border around CTRL+Tab target window
5377
0
        ImGuiWindow* window = g.NavWindowingTargetAnim;
5378
0
        ImGuiViewport* viewport = window->Viewport;
5379
0
        float distance = g.FontSize;
5380
0
        ImRect bb = window->Rect();
5381
0
        bb.Expand(distance);
5382
0
        if (bb.GetWidth() >= viewport->Size.x && bb.GetHeight() >= viewport->Size.y)
5383
0
            bb.Expand(-distance - 1.0f); // If a window fits the entire viewport, adjust its highlight inward
5384
0
        window->DrawList->ChannelsMerge();
5385
0
        if (window->DrawList->CmdBuffer.Size == 0)
5386
0
            window->DrawList->AddDrawCmd();
5387
0
        window->DrawList->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size);
5388
0
        window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), window->WindowRounding, 0, 3.0f);
5389
0
        window->DrawList->PopClipRect();
5390
0
    }
5391
5392
    // Draw dimming background on _other_ viewports than the ones our windows are in
5393
0
    for (ImGuiViewportP* viewport : g.Viewports)
5394
0
    {
5395
0
        if (viewport == viewports_already_dimmed[0] || viewport == viewports_already_dimmed[1])
5396
0
            continue;
5397
0
        if (modal_window && viewport->Window && IsWindowAbove(viewport->Window, modal_window))
5398
0
            continue;
5399
0
        ImDrawList* draw_list = GetForegroundDrawList(viewport);
5400
0
        const ImU32 dim_bg_col = GetColorU32(dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, g.DimBgRatio);
5401
0
        draw_list->AddRectFilled(viewport->Pos, viewport->Pos + viewport->Size, dim_bg_col);
5402
0
    }
5403
0
}
5404
5405
// This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal.
5406
void ImGui::EndFrame()
5407
169k
{
5408
169k
    ImGuiContext& g = *GImGui;
5409
169k
    IM_ASSERT(g.Initialized);
5410
5411
    // Don't process EndFrame() multiple times.
5412
169k
    if (g.FrameCountEnded == g.FrameCount)
5413
84.9k
        return;
5414
84.9k
    IM_ASSERT(g.WithinFrameScope && "Forgot to call ImGui::NewFrame()?");
5415
5416
84.9k
    CallContextHooks(&g, ImGuiContextHookType_EndFramePre);
5417
5418
84.9k
    ErrorCheckEndFrameSanityChecks();
5419
5420
    // Notify Platform/OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
5421
84.9k
    ImGuiPlatformImeData* ime_data = &g.PlatformImeData;
5422
84.9k
    if (g.IO.PlatformSetImeDataFn != NULL && memcmp(ime_data, &g.PlatformImeDataPrev, sizeof(ImGuiPlatformImeData)) != 0)
5423
0
    {
5424
0
        ImGuiViewport* viewport = FindViewportByID(g.PlatformImeViewport);
5425
0
        IMGUI_DEBUG_LOG_IO("[io] Calling io.PlatformSetImeDataFn(): WantVisible: %d, InputPos (%.2f,%.2f)\n", ime_data->WantVisible, ime_data->InputPos.x, ime_data->InputPos.y);
5426
0
        if (viewport == NULL)
5427
0
            viewport = GetMainViewport();
5428
0
        g.IO.PlatformSetImeDataFn(&g, viewport, ime_data);
5429
0
    }
5430
5431
    // Hide implicit/fallback "Debug" window if it hasn't been used
5432
84.9k
    g.WithinFrameScopeWithImplicitWindow = false;
5433
84.9k
    if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
5434
84.9k
        g.CurrentWindow->Active = false;
5435
84.9k
    End();
5436
5437
    // Update navigation: CTRL+Tab, wrap-around requests
5438
84.9k
    NavEndFrame();
5439
5440
    // Update docking
5441
84.9k
    DockContextEndFrame(&g);
5442
5443
84.9k
    SetCurrentViewport(NULL, NULL);
5444
5445
    // Drag and Drop: Elapse payload (if delivered, or if source stops being submitted)
5446
84.9k
    if (g.DragDropActive)
5447
0
    {
5448
0
        bool is_delivered = g.DragDropPayload.Delivery;
5449
0
        bool is_elapsed = (g.DragDropSourceFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_PayloadAutoExpire) || g.DragDropMouseButton == -1 || !IsMouseDown(g.DragDropMouseButton));
5450
0
        if (is_delivered || is_elapsed)
5451
0
            ClearDragDrop();
5452
0
    }
5453
5454
    // Drag and Drop: Fallback for missing source tooltip. This is not ideal but better than nothing.
5455
    // If you want to handle source item disappearing: instead of submitting your description tooltip
5456
    // in the BeginDragDropSource() block of the dragged item, you can submit them from a safe single spot
5457
    // (e.g. end of your item loop, or before EndFrame) by reading payload data.
5458
    // In the typical case, the contents of drag tooltip should be possible to infer solely from payload data.
5459
84.9k
    if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
5460
0
    {
5461
0
        g.DragDropWithinSource = true;
5462
0
        SetTooltip("...");
5463
0
        g.DragDropWithinSource = false;
5464
0
    }
5465
5466
    // End frame
5467
84.9k
    g.WithinFrameScope = false;
5468
84.9k
    g.FrameCountEnded = g.FrameCount;
5469
5470
    // Initiate moving window + handle left-click and right-click focus
5471
84.9k
    UpdateMouseMovingWindowEndFrame();
5472
5473
    // Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
5474
84.9k
    UpdateViewportsEndFrame();
5475
5476
    // Sort the window list so that all child windows are after their parent
5477
    // We cannot do that on FocusWindow() because children may not exist yet
5478
84.9k
    g.WindowsTempSortBuffer.resize(0);
5479
84.9k
    g.WindowsTempSortBuffer.reserve(g.Windows.Size);
5480
84.9k
    for (ImGuiWindow* window : g.Windows)
5481
254k
    {
5482
254k
        if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow))       // if a child is active its parent will add it
5483
23.7k
            continue;
5484
231k
        AddWindowToSortBuffer(&g.WindowsTempSortBuffer, window);
5485
231k
    }
5486
5487
    // This usually assert if there is a mismatch between the ImGuiWindowFlags_ChildWindow / ParentWindow values and DC.ChildWindows[] in parents, aka we've done something wrong.
5488
84.9k
    IM_ASSERT(g.Windows.Size == g.WindowsTempSortBuffer.Size);
5489
84.9k
    g.Windows.swap(g.WindowsTempSortBuffer);
5490
84.9k
    g.IO.MetricsActiveWindows = g.WindowsActiveCount;
5491
5492
    // Unlock font atlas
5493
84.9k
    g.IO.Fonts->Locked = false;
5494
5495
    // Clear Input data for next frame
5496
84.9k
    g.IO.MousePosPrev = g.IO.MousePos;
5497
84.9k
    g.IO.AppFocusLost = false;
5498
84.9k
    g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
5499
84.9k
    g.IO.InputQueueCharacters.resize(0);
5500
5501
84.9k
    CallContextHooks(&g, ImGuiContextHookType_EndFramePost);
5502
84.9k
}
5503
5504
// Prepare the data for rendering so you can call GetDrawData()
5505
// (As with anything within the ImGui:: namspace this doesn't touch your GPU or graphics API at all:
5506
// it is the role of the ImGui_ImplXXXX_RenderDrawData() function provided by the renderer backend)
5507
void ImGui::Render()
5508
84.9k
{
5509
84.9k
    ImGuiContext& g = *GImGui;
5510
84.9k
    IM_ASSERT(g.Initialized);
5511
5512
84.9k
    if (g.FrameCountEnded != g.FrameCount)
5513
84.9k
        EndFrame();
5514
84.9k
    if (g.FrameCountRendered == g.FrameCount)
5515
0
        return;
5516
84.9k
    g.FrameCountRendered = g.FrameCount;
5517
5518
84.9k
    g.IO.MetricsRenderWindows = 0;
5519
84.9k
    CallContextHooks(&g, ImGuiContextHookType_RenderPre);
5520
5521
    // Add background ImDrawList (for each active viewport)
5522
84.9k
    for (ImGuiViewportP* viewport : g.Viewports)
5523
84.9k
    {
5524
84.9k
        InitViewportDrawData(viewport);
5525
84.9k
        if (viewport->BgFgDrawLists[0] != NULL)
5526
0
            AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[0], GetBackgroundDrawList(viewport));
5527
84.9k
    }
5528
5529
    // Draw modal/window whitening backgrounds
5530
84.9k
    RenderDimmedBackgrounds();
5531
5532
    // Add ImDrawList to render
5533
84.9k
    ImGuiWindow* windows_to_render_top_most[2];
5534
84.9k
    windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindowDockTree : NULL;
5535
84.9k
    windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingListWindow : NULL);
5536
84.9k
    for (ImGuiWindow* window : g.Windows)
5537
254k
    {
5538
254k
        IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'"
5539
254k
        if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_top_most[0] && window != windows_to_render_top_most[1])
5540
84.9k
            AddRootWindowToDrawData(window);
5541
254k
    }
5542
254k
    for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_top_most); n++)
5543
169k
        if (windows_to_render_top_most[n] && IsWindowActiveAndVisible(windows_to_render_top_most[n])) // NavWindowingTarget is always temporarily displayed as the top-most window
5544
0
            AddRootWindowToDrawData(windows_to_render_top_most[n]);
5545
5546
    // Draw software mouse cursor if requested by io.MouseDrawCursor flag
5547
84.9k
    if (g.IO.MouseDrawCursor && g.MouseCursor != ImGuiMouseCursor_None)
5548
0
        RenderMouseCursor(g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor, IM_COL32_WHITE, IM_COL32_BLACK, IM_COL32(0, 0, 0, 48));
5549
5550
    // Setup ImDrawData structures for end-user
5551
84.9k
    g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = 0;
5552
84.9k
    for (ImGuiViewportP* viewport : g.Viewports)
5553
84.9k
    {
5554
84.9k
        FlattenDrawDataIntoSingleLayer(&viewport->DrawDataBuilder);
5555
5556
        // Add foreground ImDrawList (for each active viewport)
5557
84.9k
        if (viewport->BgFgDrawLists[1] != NULL)
5558
0
            AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[0], GetForegroundDrawList(viewport));
5559
5560
        // We call _PopUnusedDrawCmd() last thing, as RenderDimmedBackgrounds() rely on a valid command being there (especially in docking branch).
5561
84.9k
        ImDrawData* draw_data = &viewport->DrawDataP;
5562
84.9k
        IM_ASSERT(draw_data->CmdLists.Size == draw_data->CmdListsCount);
5563
84.9k
        for (ImDrawList* draw_list : draw_data->CmdLists)
5564
108k
            draw_list->_PopUnusedDrawCmd();
5565
5566
84.9k
        g.IO.MetricsRenderVertices += draw_data->TotalVtxCount;
5567
84.9k
        g.IO.MetricsRenderIndices += draw_data->TotalIdxCount;
5568
84.9k
    }
5569
5570
84.9k
    CallContextHooks(&g, ImGuiContextHookType_RenderPost);
5571
84.9k
}
5572
5573
// Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
5574
// CalcTextSize("") should return ImVec2(0.0f, g.FontSize)
5575
ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
5576
169k
{
5577
169k
    ImGuiContext& g = *GImGui;
5578
5579
169k
    const char* text_display_end;
5580
169k
    if (hide_text_after_double_hash)
5581
169k
        text_display_end = FindRenderedTextEnd(text, text_end);      // Hide anything after a '##' string
5582
0
    else
5583
0
        text_display_end = text_end;
5584
5585
169k
    ImFont* font = g.Font;
5586
169k
    const float font_size = g.FontSize;
5587
169k
    if (text == text_display_end)
5588
0
        return ImVec2(0.0f, font_size);
5589
169k
    ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL);
5590
5591
    // Round
5592
    // FIXME: This has been here since Dec 2015 (7b0bf230) but down the line we want this out.
5593
    // FIXME: Investigate using ceilf or e.g.
5594
    // - https://git.musl-libc.org/cgit/musl/tree/src/math/ceilf.c
5595
    // - https://embarkstudios.github.io/rust-gpu/api/src/libm/math/ceilf.rs.html
5596
169k
    text_size.x = IM_TRUNC(text_size.x + 0.99999f);
5597
5598
169k
    return text_size;
5599
169k
}
5600
5601
// Find window given position, search front-to-back
5602
// - Typically write output back to g.HoveredWindow and g.HoveredWindowUnderMovingWindow.
5603
// - FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programmatically
5604
//   with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is
5605
//   called, aka before the next Begin(). Moving window isn't affected.
5606
// - The 'find_first_and_in_any_viewport = true' mode is only used by TestEngine. It is simpler to maintain here.
5607
void ImGui::FindHoveredWindowEx(const ImVec2& pos, bool find_first_and_in_any_viewport, ImGuiWindow** out_hovered_window, ImGuiWindow** out_hovered_window_under_moving_window)
5608
84.9k
{
5609
84.9k
    ImGuiContext& g = *GImGui;
5610
84.9k
    ImGuiWindow* hovered_window = NULL;
5611
84.9k
    ImGuiWindow* hovered_window_under_moving_window = NULL;
5612
5613
    // Special handling for the window being moved: Ignore the mouse viewport check (because it may reset/lose its viewport during the undocking frame)
5614
84.9k
    ImGuiViewportP* backup_moving_window_viewport = NULL;
5615
84.9k
    if (find_first_and_in_any_viewport == false && g.MovingWindow)
5616
1
    {
5617
1
        backup_moving_window_viewport = g.MovingWindow->Viewport;
5618
1
        g.MovingWindow->Viewport = g.MouseViewport;
5619
1
        if (!(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs))
5620
1
            hovered_window = g.MovingWindow;
5621
1
    }
5622
5623
84.9k
    ImVec2 padding_regular = g.Style.TouchExtraPadding;
5624
84.9k
    ImVec2 padding_for_resize = g.IO.ConfigWindowsResizeFromEdges ? g.WindowsHoverPadding : padding_regular;
5625
333k
    for (int i = g.Windows.Size - 1; i >= 0; i--)
5626
251k
    {
5627
251k
        ImGuiWindow* window = g.Windows[i];
5628
251k
        IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
5629
251k
        if (!window->Active || window->Hidden)
5630
143k
            continue;
5631
108k
        if (window->Flags & ImGuiWindowFlags_NoMouseInputs)
5632
0
            continue;
5633
108k
        IM_ASSERT(window->Viewport);
5634
108k
        if (window->Viewport != g.MouseViewport)
5635
0
            continue;
5636
5637
        // Using the clipped AABB, a child window will typically be clipped by its parent (not always)
5638
108k
        ImVec2 hit_padding = (window->Flags & (ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize)) ? padding_regular : padding_for_resize;
5639
108k
        if (!window->OuterRectClipped.ContainsWithPad(pos, hit_padding))
5640
105k
            continue;
5641
5642
        // Support for one rectangular hole in any given window
5643
        // FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512)
5644
3.08k
        if (window->HitTestHoleSize.x != 0)
5645
0
        {
5646
0
            ImVec2 hole_pos(window->Pos.x + (float)window->HitTestHoleOffset.x, window->Pos.y + (float)window->HitTestHoleOffset.y);
5647
0
            ImVec2 hole_size((float)window->HitTestHoleSize.x, (float)window->HitTestHoleSize.y);
5648
0
            if (ImRect(hole_pos, hole_pos + hole_size).Contains(pos))
5649
0
                continue;
5650
0
        }
5651
5652
3.08k
        if (find_first_and_in_any_viewport)
5653
0
        {
5654
0
            hovered_window = window;
5655
0
            break;
5656
0
        }
5657
3.08k
        else
5658
3.08k
        {
5659
3.08k
            if (hovered_window == NULL)
5660
3.08k
                hovered_window = window;
5661
3.08k
            IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
5662
3.08k
            if (hovered_window_under_moving_window == NULL && (!g.MovingWindow || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree))
5663
3.08k
                hovered_window_under_moving_window = window;
5664
3.08k
            if (hovered_window && hovered_window_under_moving_window)
5665
3.08k
                break;
5666
3.08k
        }
5667
3.08k
    }
5668
5669
84.9k
    *out_hovered_window = hovered_window;
5670
84.9k
    if (out_hovered_window_under_moving_window != NULL)
5671
84.9k
        *out_hovered_window_under_moving_window = hovered_window_under_moving_window;
5672
84.9k
    if (find_first_and_in_any_viewport == false && g.MovingWindow)
5673
1
        g.MovingWindow->Viewport = backup_moving_window_viewport;
5674
84.9k
}
5675
5676
bool ImGui::IsItemActive()
5677
169k
{
5678
169k
    ImGuiContext& g = *GImGui;
5679
169k
    if (g.ActiveId)
5680
42
        return g.ActiveId == g.LastItemData.ID;
5681
169k
    return false;
5682
169k
}
5683
5684
bool ImGui::IsItemActivated()
5685
0
{
5686
0
    ImGuiContext& g = *GImGui;
5687
0
    if (g.ActiveId)
5688
0
        if (g.ActiveId == g.LastItemData.ID && g.ActiveIdPreviousFrame != g.LastItemData.ID)
5689
0
            return true;
5690
0
    return false;
5691
0
}
5692
5693
bool ImGui::IsItemDeactivated()
5694
0
{
5695
0
    ImGuiContext& g = *GImGui;
5696
0
    if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDeactivated)
5697
0
        return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Deactivated) != 0;
5698
0
    return (g.ActiveIdPreviousFrame == g.LastItemData.ID && g.ActiveIdPreviousFrame != 0 && g.ActiveId != g.LastItemData.ID);
5699
0
}
5700
5701
bool ImGui::IsItemDeactivatedAfterEdit()
5702
0
{
5703
0
    ImGuiContext& g = *GImGui;
5704
0
    return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEditedBefore || (g.ActiveId == 0 && g.ActiveIdHasBeenEditedBefore));
5705
0
}
5706
5707
// == GetItemID() == GetFocusID()
5708
bool ImGui::IsItemFocused()
5709
0
{
5710
0
    ImGuiContext& g = *GImGui;
5711
0
    if (g.NavId != g.LastItemData.ID || g.NavId == 0)
5712
0
        return false;
5713
5714
    // Special handling for the dummy item after Begin() which represent the title bar or tab.
5715
    // When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case.
5716
0
    ImGuiWindow* window = g.CurrentWindow;
5717
0
    if (g.LastItemData.ID == window->ID && window->WriteAccessed)
5718
0
        return false;
5719
5720
0
    return true;
5721
0
}
5722
5723
// Important: this can be useful but it is NOT equivalent to the behavior of e.g.Button()!
5724
// Most widgets have specific reactions based on mouse-up/down state, mouse position etc.
5725
bool ImGui::IsItemClicked(ImGuiMouseButton mouse_button)
5726
0
{
5727
0
    return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_None);
5728
0
}
5729
5730
bool ImGui::IsItemToggledOpen()
5731
0
{
5732
0
    ImGuiContext& g = *GImGui;
5733
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledOpen) ? true : false;
5734
0
}
5735
5736
// Call after a Selectable() or TreeNode() involved in multi-selection.
5737
// Useful if you need the per-item information before reaching EndMultiSelect(), e.g. for rendering purpose.
5738
// This is only meant to be called inside a BeginMultiSelect()/EndMultiSelect() block.
5739
// (Outside of multi-select, it would be misleading/ambiguous to report this signal, as widgets
5740
// return e.g. a pressed event and user code is in charge of altering selection in ways we cannot predict.)
5741
bool ImGui::IsItemToggledSelection()
5742
0
{
5743
0
    ImGuiContext& g = *GImGui;
5744
0
    IM_ASSERT(g.CurrentMultiSelect != NULL); // Can only be used inside a BeginMultiSelect()/EndMultiSelect()
5745
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledSelection) ? true : false;
5746
0
}
5747
5748
// IMPORTANT: If you are trying to check whether your mouse should be dispatched to Dear ImGui or to your underlying app,
5749
// you should not use this function! Use the 'io.WantCaptureMouse' boolean for that!
5750
// Refer to FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" for details.
5751
bool ImGui::IsAnyItemHovered()
5752
0
{
5753
0
    ImGuiContext& g = *GImGui;
5754
0
    return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0;
5755
0
}
5756
5757
bool ImGui::IsAnyItemActive()
5758
0
{
5759
0
    ImGuiContext& g = *GImGui;
5760
0
    return g.ActiveId != 0;
5761
0
}
5762
5763
bool ImGui::IsAnyItemFocused()
5764
0
{
5765
0
    ImGuiContext& g = *GImGui;
5766
0
    return g.NavId != 0 && !g.NavDisableHighlight;
5767
0
}
5768
5769
bool ImGui::IsItemVisible()
5770
0
{
5771
0
    ImGuiContext& g = *GImGui;
5772
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible) != 0;
5773
0
}
5774
5775
bool ImGui::IsItemEdited()
5776
0
{
5777
0
    ImGuiContext& g = *GImGui;
5778
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Edited) != 0;
5779
0
}
5780
5781
// Allow next item to be overlapped by subsequent items.
5782
// This works by requiring HoveredId to match for two subsequent frames,
5783
// so if a following items overwrite it our interactions will naturally be disabled.
5784
void ImGui::SetNextItemAllowOverlap()
5785
0
{
5786
0
    ImGuiContext& g = *GImGui;
5787
0
    g.NextItemData.ItemFlags |= ImGuiItemFlags_AllowOverlap;
5788
0
}
5789
5790
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
5791
// Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
5792
// FIXME-LEGACY: Use SetNextItemAllowOverlap() *before* your item instead.
5793
void ImGui::SetItemAllowOverlap()
5794
{
5795
    ImGuiContext& g = *GImGui;
5796
    ImGuiID id = g.LastItemData.ID;
5797
    if (g.HoveredId == id)
5798
        g.HoveredIdAllowOverlap = true;
5799
    if (g.ActiveId == id) // Before we made this obsolete, most calls to SetItemAllowOverlap() used to avoid this path by testing g.ActiveId != id.
5800
        g.ActiveIdAllowOverlap = true;
5801
}
5802
#endif
5803
5804
// This is a shortcut for not taking ownership of 100+ keys, frequently used by drag operations.
5805
// FIXME: It might be undesirable that this will likely disable KeyOwner-aware shortcuts systems. Consider a more fine-tuned version if needed?
5806
void ImGui::SetActiveIdUsingAllKeyboardKeys()
5807
1
{
5808
1
    ImGuiContext& g = *GImGui;
5809
1
    IM_ASSERT(g.ActiveId != 0);
5810
1
    g.ActiveIdUsingNavDirMask = (1 << ImGuiDir_COUNT) - 1;
5811
1
    g.ActiveIdUsingAllKeyboardKeys = true;
5812
1
    NavMoveRequestCancel();
5813
1
}
5814
5815
ImGuiID ImGui::GetItemID()
5816
0
{
5817
0
    ImGuiContext& g = *GImGui;
5818
0
    return g.LastItemData.ID;
5819
0
}
5820
5821
ImVec2 ImGui::GetItemRectMin()
5822
0
{
5823
0
    ImGuiContext& g = *GImGui;
5824
0
    return g.LastItemData.Rect.Min;
5825
0
}
5826
5827
ImVec2 ImGui::GetItemRectMax()
5828
0
{
5829
0
    ImGuiContext& g = *GImGui;
5830
0
    return g.LastItemData.Rect.Max;
5831
0
}
5832
5833
ImVec2 ImGui::GetItemRectSize()
5834
0
{
5835
0
    ImGuiContext& g = *GImGui;
5836
0
    return g.LastItemData.Rect.GetSize();
5837
0
}
5838
5839
// Prior to v1.90 2023/10/16, the BeginChild() function took a 'bool border = false' parameter instead of 'ImGuiChildFlags child_flags = 0'.
5840
// ImGuiChildFlags_Border is defined as always == 1 in order to allow old code passing 'true'. Read comments in imgui.h for details!
5841
bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
5842
23.7k
{
5843
23.7k
    ImGuiID id = GetCurrentWindow()->GetID(str_id);
5844
23.7k
    return BeginChildEx(str_id, id, size_arg, child_flags, window_flags);
5845
23.7k
}
5846
5847
bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
5848
0
{
5849
0
    return BeginChildEx(NULL, id, size_arg, child_flags, window_flags);
5850
0
}
5851
5852
bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
5853
23.7k
{
5854
23.7k
    ImGuiContext& g = *GImGui;
5855
23.7k
    ImGuiWindow* parent_window = g.CurrentWindow;
5856
23.7k
    IM_ASSERT(id != 0);
5857
5858
    // Sanity check as it is likely that some user will accidentally pass ImGuiWindowFlags into the ImGuiChildFlags argument.
5859
23.7k
    const ImGuiChildFlags ImGuiChildFlags_SupportedMask_ = ImGuiChildFlags_Border | ImGuiChildFlags_AlwaysUseWindowPadding | ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY | ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_AlwaysAutoResize | ImGuiChildFlags_FrameStyle | ImGuiChildFlags_NavFlattened;
5860
23.7k
    IM_UNUSED(ImGuiChildFlags_SupportedMask_);
5861
23.7k
    IM_ASSERT((child_flags & ~ImGuiChildFlags_SupportedMask_) == 0 && "Illegal ImGuiChildFlags value. Did you pass ImGuiWindowFlags values instead of ImGuiChildFlags?");
5862
23.7k
    IM_ASSERT((window_flags & ImGuiWindowFlags_AlwaysAutoResize) == 0 && "Cannot specify ImGuiWindowFlags_AlwaysAutoResize for BeginChild(). Use ImGuiChildFlags_AlwaysAutoResize!");
5863
23.7k
    if (child_flags & ImGuiChildFlags_AlwaysAutoResize)
5864
0
    {
5865
0
        IM_ASSERT((child_flags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0 && "Cannot use ImGuiChildFlags_ResizeX or ImGuiChildFlags_ResizeY with ImGuiChildFlags_AlwaysAutoResize!");
5866
0
        IM_ASSERT((child_flags & (ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY)) != 0 && "Must use ImGuiChildFlags_AutoResizeX or ImGuiChildFlags_AutoResizeY with ImGuiChildFlags_AlwaysAutoResize!");
5867
0
    }
5868
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
5869
    if (window_flags & ImGuiWindowFlags_AlwaysUseWindowPadding)
5870
        child_flags |= ImGuiChildFlags_AlwaysUseWindowPadding;
5871
    if (window_flags & ImGuiWindowFlags_NavFlattened)
5872
        child_flags |= ImGuiChildFlags_NavFlattened;
5873
#endif
5874
23.7k
    if (child_flags & ImGuiChildFlags_AutoResizeX)
5875
0
        child_flags &= ~ImGuiChildFlags_ResizeX;
5876
23.7k
    if (child_flags & ImGuiChildFlags_AutoResizeY)
5877
0
        child_flags &= ~ImGuiChildFlags_ResizeY;
5878
5879
    // Set window flags
5880
23.7k
    window_flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking;
5881
23.7k
    window_flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove); // Inherit the NoMove flag
5882
23.7k
    if (child_flags & (ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_AlwaysAutoResize))
5883
0
        window_flags |= ImGuiWindowFlags_AlwaysAutoResize;
5884
23.7k
    if ((child_flags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0)
5885
23.7k
        window_flags |= ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings;
5886
5887
    // Special framed style
5888
23.7k
    if (child_flags & ImGuiChildFlags_FrameStyle)
5889
0
    {
5890
0
        PushStyleColor(ImGuiCol_ChildBg, g.Style.Colors[ImGuiCol_FrameBg]);
5891
0
        PushStyleVar(ImGuiStyleVar_ChildRounding, g.Style.FrameRounding);
5892
0
        PushStyleVar(ImGuiStyleVar_ChildBorderSize, g.Style.FrameBorderSize);
5893
0
        PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.FramePadding);
5894
0
        child_flags |= ImGuiChildFlags_Border | ImGuiChildFlags_AlwaysUseWindowPadding;
5895
0
        window_flags |= ImGuiWindowFlags_NoMove;
5896
0
    }
5897
5898
    // Forward child flags
5899
23.7k
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasChildFlags;
5900
23.7k
    g.NextWindowData.ChildFlags = child_flags;
5901
5902
    // Forward size
5903
    // Important: Begin() has special processing to switch condition to ImGuiCond_FirstUseEver for a given axis when ImGuiChildFlags_ResizeXXX is set.
5904
    // (the alternative would to store conditional flags per axis, which is possible but more code)
5905
23.7k
    const ImVec2 size_avail = GetContentRegionAvail();
5906
23.7k
    const ImVec2 size_default((child_flags & ImGuiChildFlags_AutoResizeX) ? 0.0f : size_avail.x, (child_flags & ImGuiChildFlags_AutoResizeY) ? 0.0f : size_avail.y);
5907
23.7k
    const ImVec2 size = CalcItemSize(size_arg, size_default.x, size_default.y);
5908
23.7k
    SetNextWindowSize(size);
5909
5910
    // Build up name. If you need to append to a same child from multiple location in the ID stack, use BeginChild(ImGuiID id) with a stable value.
5911
    // FIXME: 2023/11/14: commented out shorted version. We had an issue with multiple ### in child window path names, which the trailing hash helped workaround.
5912
    // e.g. "ParentName###ParentIdentifier/ChildName###ChildIdentifier" would get hashed incorrectly by ImHashStr(), trailing _%08X somehow fixes it.
5913
23.7k
    const char* temp_window_name;
5914
    /*if (name && parent_window->IDStack.back() == parent_window->ID)
5915
        ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%s", parent_window->Name, name); // May omit ID if in root of ID stack
5916
    else*/
5917
23.7k
    if (name)
5918
23.7k
        ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%s_%08X", parent_window->Name, name, id);
5919
0
    else
5920
0
        ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%08X", parent_window->Name, id);
5921
5922
    // Set style
5923
23.7k
    const float backup_border_size = g.Style.ChildBorderSize;
5924
23.7k
    if ((child_flags & ImGuiChildFlags_Border) == 0)
5925
10.5k
        g.Style.ChildBorderSize = 0.0f;
5926
5927
    // Begin into window
5928
23.7k
    const bool ret = Begin(temp_window_name, NULL, window_flags);
5929
5930
    // Restore style
5931
23.7k
    g.Style.ChildBorderSize = backup_border_size;
5932
23.7k
    if (child_flags & ImGuiChildFlags_FrameStyle)
5933
0
    {
5934
0
        PopStyleVar(3);
5935
0
        PopStyleColor();
5936
0
    }
5937
5938
23.7k
    ImGuiWindow* child_window = g.CurrentWindow;
5939
23.7k
    child_window->ChildId = id;
5940
5941
    // Set the cursor to handle case where the user called SetNextWindowPos()+BeginChild() manually.
5942
    // While this is not really documented/defined, it seems that the expected thing to do.
5943
23.7k
    if (child_window->BeginCount == 1)
5944
23.7k
        parent_window->DC.CursorPos = child_window->Pos;
5945
5946
    // Process navigation-in immediately so NavInit can run on first frame
5947
    // Can enter a child if (A) it has navigable items or (B) it can be scrolled.
5948
23.7k
    const ImGuiID temp_id_for_activation = ImHashStr("##Child", 0, id);
5949
23.7k
    if (g.ActiveId == temp_id_for_activation)
5950
20
        ClearActiveID();
5951
23.7k
    if (g.NavActivateId == id && !(child_flags & ImGuiChildFlags_NavFlattened) && (child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY))
5952
27
    {
5953
27
        FocusWindow(child_window);
5954
27
        NavInitWindow(child_window, false);
5955
27
        SetActiveID(temp_id_for_activation, child_window); // Steal ActiveId with another arbitrary id so that key-press won't activate child item
5956
27
        g.ActiveIdSource = g.NavInputSource;
5957
27
    }
5958
23.7k
    return ret;
5959
23.7k
}
5960
5961
void ImGui::EndChild()
5962
23.7k
{
5963
23.7k
    ImGuiContext& g = *GImGui;
5964
23.7k
    ImGuiWindow* child_window = g.CurrentWindow;
5965
5966
23.7k
    IM_ASSERT(g.WithinEndChild == false);
5967
23.7k
    IM_ASSERT(child_window->Flags & ImGuiWindowFlags_ChildWindow);   // Mismatched BeginChild()/EndChild() calls
5968
5969
23.7k
    g.WithinEndChild = true;
5970
23.7k
    ImVec2 child_size = child_window->Size;
5971
23.7k
    End();
5972
23.7k
    if (child_window->BeginCount == 1)
5973
23.7k
    {
5974
23.7k
        ImGuiWindow* parent_window = g.CurrentWindow;
5975
23.7k
        ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + child_size);
5976
23.7k
        ItemSize(child_size);
5977
23.7k
        const bool nav_flattened = (child_window->ChildFlags & ImGuiChildFlags_NavFlattened) != 0;
5978
23.7k
        if ((child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY) && !nav_flattened)
5979
19.2k
        {
5980
19.2k
            ItemAdd(bb, child_window->ChildId);
5981
19.2k
            RenderNavHighlight(bb, child_window->ChildId);
5982
5983
            // When browsing a window that has no activable items (scroll only) we keep a highlight on the child (pass g.NavId to trick into always displaying)
5984
19.2k
            if (child_window->DC.NavLayersActiveMask == 0 && child_window == g.NavWindow)
5985
13.4k
                RenderNavHighlight(ImRect(bb.Min - ImVec2(2, 2), bb.Max + ImVec2(2, 2)), g.NavId, ImGuiNavHighlightFlags_Compact);
5986
19.2k
        }
5987
4.42k
        else
5988
4.42k
        {
5989
            // Not navigable into
5990
            // - This is a bit of a fringe use case, mostly useful for undecorated, non-scrolling contents childs, or empty childs.
5991
            // - We could later decide to not apply this path if ImGuiChildFlags_FrameStyle or ImGuiChildFlags_Borders is set.
5992
4.42k
            ItemAdd(bb, child_window->ChildId, NULL, ImGuiItemFlags_NoNav);
5993
5994
            // But when flattened we directly reach items, adjust active layer mask accordingly
5995
4.42k
            if (nav_flattened)
5996
0
                parent_window->DC.NavLayersActiveMaskNext |= child_window->DC.NavLayersActiveMaskNext;
5997
4.42k
        }
5998
23.7k
        if (g.HoveredWindow == child_window)
5999
10
            g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
6000
23.7k
    }
6001
23.7k
    g.WithinEndChild = false;
6002
23.7k
    g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
6003
23.7k
}
6004
6005
static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled)
6006
6
{
6007
6
    window->SetWindowPosAllowFlags       = enabled ? (window->SetWindowPosAllowFlags       | flags) : (window->SetWindowPosAllowFlags       & ~flags);
6008
6
    window->SetWindowSizeAllowFlags      = enabled ? (window->SetWindowSizeAllowFlags      | flags) : (window->SetWindowSizeAllowFlags      & ~flags);
6009
6
    window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags);
6010
6
    window->SetWindowDockAllowFlags      = enabled ? (window->SetWindowDockAllowFlags      | flags) : (window->SetWindowDockAllowFlags      & ~flags);
6011
6
}
6012
6013
ImGuiWindow* ImGui::FindWindowByID(ImGuiID id)
6014
193k
{
6015
193k
    ImGuiContext& g = *GImGui;
6016
193k
    return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id);
6017
193k
}
6018
6019
ImGuiWindow* ImGui::FindWindowByName(const char* name)
6020
193k
{
6021
193k
    ImGuiID id = ImHashStr(name);
6022
193k
    return FindWindowByID(id);
6023
193k
}
6024
6025
static void ApplyWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
6026
0
{
6027
0
    const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
6028
0
    window->ViewportPos = main_viewport->Pos;
6029
0
    if (settings->ViewportId)
6030
0
    {
6031
0
        window->ViewportId = settings->ViewportId;
6032
0
        window->ViewportPos = ImVec2(settings->ViewportPos.x, settings->ViewportPos.y);
6033
0
    }
6034
0
    window->Pos = ImTrunc(ImVec2(settings->Pos.x + window->ViewportPos.x, settings->Pos.y + window->ViewportPos.y));
6035
0
    if (settings->Size.x > 0 && settings->Size.y > 0)
6036
0
        window->Size = window->SizeFull = ImTrunc(ImVec2(settings->Size.x, settings->Size.y));
6037
0
    window->Collapsed = settings->Collapsed;
6038
0
    window->DockId = settings->DockId;
6039
0
    window->DockOrder = settings->DockOrder;
6040
0
}
6041
6042
static void UpdateWindowInFocusOrderList(ImGuiWindow* window, bool just_created, ImGuiWindowFlags new_flags)
6043
193k
{
6044
193k
    ImGuiContext& g = *GImGui;
6045
6046
193k
    const bool new_is_explicit_child = (new_flags & ImGuiWindowFlags_ChildWindow) != 0 && ((new_flags & ImGuiWindowFlags_Popup) == 0 || (new_flags & ImGuiWindowFlags_ChildMenu) != 0);
6047
193k
    const bool child_flag_changed = new_is_explicit_child != window->IsExplicitChild;
6048
193k
    if ((just_created || child_flag_changed) && !new_is_explicit_child)
6049
2
    {
6050
2
        IM_ASSERT(!g.WindowsFocusOrder.contains(window));
6051
2
        g.WindowsFocusOrder.push_back(window);
6052
2
        window->FocusOrder = (short)(g.WindowsFocusOrder.Size - 1);
6053
2
    }
6054
193k
    else if (!just_created && child_flag_changed && new_is_explicit_child)
6055
0
    {
6056
0
        IM_ASSERT(g.WindowsFocusOrder[window->FocusOrder] == window);
6057
0
        for (int n = window->FocusOrder + 1; n < g.WindowsFocusOrder.Size; n++)
6058
0
            g.WindowsFocusOrder[n]->FocusOrder--;
6059
0
        g.WindowsFocusOrder.erase(g.WindowsFocusOrder.Data + window->FocusOrder);
6060
0
        window->FocusOrder = -1;
6061
0
    }
6062
193k
    window->IsExplicitChild = new_is_explicit_child;
6063
193k
}
6064
6065
static void InitOrLoadWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
6066
3
{
6067
    // Initial window state with e.g. default/arbitrary window position
6068
    // Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
6069
3
    const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
6070
3
    window->Pos = main_viewport->Pos + ImVec2(60, 60);
6071
3
    window->Size = window->SizeFull = ImVec2(0, 0);
6072
3
    window->ViewportPos = main_viewport->Pos;
6073
3
    window->SetWindowPosAllowFlags = window->SetWindowSizeAllowFlags = window->SetWindowCollapsedAllowFlags = window->SetWindowDockAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
6074
6075
3
    if (settings != NULL)
6076
0
    {
6077
0
        SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false);
6078
0
        ApplyWindowSettings(window, settings);
6079
0
    }
6080
3
    window->DC.CursorStartPos = window->DC.CursorMaxPos = window->DC.IdealMaxPos = window->Pos; // So first call to CalcWindowContentSizes() doesn't return crazy values
6081
6082
3
    if ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
6083
0
    {
6084
0
        window->AutoFitFramesX = window->AutoFitFramesY = 2;
6085
0
        window->AutoFitOnlyGrows = false;
6086
0
    }
6087
3
    else
6088
3
    {
6089
3
        if (window->Size.x <= 0.0f)
6090
3
            window->AutoFitFramesX = 2;
6091
3
        if (window->Size.y <= 0.0f)
6092
3
            window->AutoFitFramesY = 2;
6093
3
        window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0);
6094
3
    }
6095
3
}
6096
6097
static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags)
6098
3
{
6099
    // Create window the first time
6100
    //IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags);
6101
3
    ImGuiContext& g = *GImGui;
6102
3
    ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name);
6103
3
    window->Flags = flags;
6104
3
    g.WindowsById.SetVoidPtr(window->ID, window);
6105
6106
3
    ImGuiWindowSettings* settings = NULL;
6107
3
    if (!(flags & ImGuiWindowFlags_NoSavedSettings))
6108
2
        if ((settings = ImGui::FindWindowSettingsByWindow(window)) != 0)
6109
0
            window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
6110
6111
3
    InitOrLoadWindowSettings(window, settings);
6112
6113
3
    if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
6114
0
        g.Windows.push_front(window); // Quite slow but rare and only once
6115
3
    else
6116
3
        g.Windows.push_back(window);
6117
6118
3
    return window;
6119
3
}
6120
6121
static ImGuiWindow* GetWindowForTitleDisplay(ImGuiWindow* window)
6122
0
{
6123
0
    return window->DockNodeAsHost ? window->DockNodeAsHost->VisibleWindow : window;
6124
0
}
6125
6126
static ImGuiWindow* GetWindowForTitleAndMenuHeight(ImGuiWindow* window)
6127
580k
{
6128
580k
    return (window->DockNodeAsHost && window->DockNodeAsHost->VisibleWindow) ? window->DockNodeAsHost->VisibleWindow : window;
6129
580k
}
6130
6131
static inline ImVec2 CalcWindowMinSize(ImGuiWindow* window)
6132
580k
{
6133
    // We give windows non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups)
6134
    // FIXME: Essentially we want to restrict manual resizing to WindowMinSize+Decoration, and allow api resizing to be smaller.
6135
    // Perhaps should tend further a neater test for this.
6136
580k
    ImGuiContext& g = *GImGui;
6137
580k
    ImVec2 size_min;
6138
580k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_Popup))
6139
71.1k
    {
6140
71.1k
        size_min.x = (window->ChildFlags & ImGuiChildFlags_ResizeX) ? g.Style.WindowMinSize.x : 4.0f;
6141
71.1k
        size_min.y = (window->ChildFlags & ImGuiChildFlags_ResizeY) ? g.Style.WindowMinSize.y : 4.0f;
6142
71.1k
    }
6143
509k
    else
6144
509k
    {
6145
509k
        size_min.x = ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) == 0) ? g.Style.WindowMinSize.x : 4.0f;
6146
509k
        size_min.y = ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) == 0) ? g.Style.WindowMinSize.y : 4.0f;
6147
509k
    }
6148
6149
    // Reduce artifacts with very small windows
6150
580k
    ImGuiWindow* window_for_height = GetWindowForTitleAndMenuHeight(window);
6151
580k
    size_min.y = ImMax(size_min.y, window_for_height->TitleBarHeight + window_for_height->MenuBarHeight + ImMax(0.0f, g.Style.WindowRounding - 1.0f));
6152
580k
    return size_min;
6153
580k
}
6154
6155
static ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow* window, const ImVec2& size_desired)
6156
387k
{
6157
387k
    ImGuiContext& g = *GImGui;
6158
387k
    ImVec2 new_size = size_desired;
6159
387k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint)
6160
0
    {
6161
        // See comments in SetNextWindowSizeConstraints() for details about setting size_min an size_max.
6162
0
        ImRect cr = g.NextWindowData.SizeConstraintRect;
6163
0
        new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x;
6164
0
        new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y;
6165
0
        if (g.NextWindowData.SizeCallback)
6166
0
        {
6167
0
            ImGuiSizeCallbackData data;
6168
0
            data.UserData = g.NextWindowData.SizeCallbackUserData;
6169
0
            data.Pos = window->Pos;
6170
0
            data.CurrentSize = window->SizeFull;
6171
0
            data.DesiredSize = new_size;
6172
0
            g.NextWindowData.SizeCallback(&data);
6173
0
            new_size = data.DesiredSize;
6174
0
        }
6175
0
        new_size.x = IM_TRUNC(new_size.x);
6176
0
        new_size.y = IM_TRUNC(new_size.y);
6177
0
    }
6178
6179
    // Minimum size
6180
387k
    ImVec2 size_min = CalcWindowMinSize(window);
6181
387k
    return ImMax(new_size, size_min);
6182
387k
}
6183
6184
static void CalcWindowContentSizes(ImGuiWindow* window, ImVec2* content_size_current, ImVec2* content_size_ideal)
6185
193k
{
6186
193k
    bool preserve_old_content_sizes = false;
6187
193k
    if (window->Collapsed && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
6188
61.2k
        preserve_old_content_sizes = true;
6189
132k
    else if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0)
6190
0
        preserve_old_content_sizes = true;
6191
193k
    if (preserve_old_content_sizes)
6192
61.2k
    {
6193
61.2k
        *content_size_current = window->ContentSize;
6194
61.2k
        *content_size_ideal = window->ContentSizeIdeal;
6195
61.2k
        return;
6196
61.2k
    }
6197
6198
132k
    content_size_current->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_TRUNC(window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x);
6199
132k
    content_size_current->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_TRUNC(window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y);
6200
132k
    content_size_ideal->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_TRUNC(ImMax(window->DC.CursorMaxPos.x, window->DC.IdealMaxPos.x) - window->DC.CursorStartPos.x);
6201
132k
    content_size_ideal->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_TRUNC(ImMax(window->DC.CursorMaxPos.y, window->DC.IdealMaxPos.y) - window->DC.CursorStartPos.y);
6202
132k
}
6203
6204
static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents)
6205
193k
{
6206
193k
    ImGuiContext& g = *GImGui;
6207
193k
    ImGuiStyle& style = g.Style;
6208
193k
    const float decoration_w_without_scrollbars = window->DecoOuterSizeX1 + window->DecoOuterSizeX2 - window->ScrollbarSizes.x;
6209
193k
    const float decoration_h_without_scrollbars = window->DecoOuterSizeY1 + window->DecoOuterSizeY2 - window->ScrollbarSizes.y;
6210
193k
    ImVec2 size_pad = window->WindowPadding * 2.0f;
6211
193k
    ImVec2 size_desired = size_contents + size_pad + ImVec2(decoration_w_without_scrollbars, decoration_h_without_scrollbars);
6212
193k
    if (window->Flags & ImGuiWindowFlags_Tooltip)
6213
0
    {
6214
        // Tooltip always resize
6215
0
        return size_desired;
6216
0
    }
6217
193k
    else
6218
193k
    {
6219
        // Maximum window size is determined by the viewport size or monitor size
6220
193k
        ImVec2 size_min = CalcWindowMinSize(window);
6221
193k
        ImVec2 size_max = ImVec2(FLT_MAX, FLT_MAX);
6222
6223
        // Child windows are layed within their parent (unless they are also popups/menus) and thus have no restriction
6224
193k
        if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || (window->Flags & ImGuiWindowFlags_Popup) != 0)
6225
169k
        {
6226
169k
            if (!window->ViewportOwned)
6227
169k
                size_max = ImGui::GetMainViewport()->WorkSize - style.DisplaySafeAreaPadding * 2.0f;
6228
169k
            const int monitor_idx = window->ViewportAllowPlatformMonitorExtend;
6229
169k
            if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
6230
0
                size_max = g.PlatformIO.Monitors[monitor_idx].WorkSize - style.DisplaySafeAreaPadding * 2.0f;
6231
169k
        }
6232
6233
193k
        ImVec2 size_auto_fit = ImClamp(size_desired, size_min, ImMax(size_min, size_max));
6234
6235
        // FIXME: CalcWindowAutoFitSize() doesn't take into account that only one axis may be auto-fit when calculating scrollbars,
6236
        // we may need to compute/store three variants of size_auto_fit, for x/y/xy.
6237
        // Here we implement a workaround for child windows only, but a full solution would apply to normal windows as well:
6238
193k
        if ((window->ChildFlags & ImGuiChildFlags_ResizeX) && !(window->ChildFlags & ImGuiChildFlags_ResizeY))
6239
0
            size_auto_fit.y = window->SizeFull.y;
6240
193k
        else if (!(window->ChildFlags & ImGuiChildFlags_ResizeX) && (window->ChildFlags & ImGuiChildFlags_ResizeY))
6241
0
            size_auto_fit.x = window->SizeFull.x;
6242
6243
        // When the window cannot fit all contents (either because of constraints, either because screen is too small),
6244
        // we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding.
6245
193k
        ImVec2 size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6246
193k
        bool will_have_scrollbar_x = (size_auto_fit_after_constraint.x - size_pad.x - decoration_w_without_scrollbars < size_contents.x && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar);
6247
193k
        bool will_have_scrollbar_y = (size_auto_fit_after_constraint.y - size_pad.y - decoration_h_without_scrollbars < size_contents.y && !(window->Flags & ImGuiWindowFlags_NoScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysVerticalScrollbar);
6248
193k
        if (will_have_scrollbar_x)
6249
23.7k
            size_auto_fit.y += style.ScrollbarSize;
6250
193k
        if (will_have_scrollbar_y)
6251
1.49k
            size_auto_fit.x += style.ScrollbarSize;
6252
193k
        return size_auto_fit;
6253
193k
    }
6254
193k
}
6255
6256
ImVec2 ImGui::CalcWindowNextAutoFitSize(ImGuiWindow* window)
6257
0
{
6258
0
    ImVec2 size_contents_current;
6259
0
    ImVec2 size_contents_ideal;
6260
0
    CalcWindowContentSizes(window, &size_contents_current, &size_contents_ideal);
6261
0
    ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents_ideal);
6262
0
    ImVec2 size_final = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6263
0
    return size_final;
6264
0
}
6265
6266
static ImGuiCol GetWindowBgColorIdx(ImGuiWindow* window)
6267
132k
{
6268
132k
    if (window->Flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
6269
0
        return ImGuiCol_PopupBg;
6270
132k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !window->DockIsActive)
6271
23.7k
        return ImGuiCol_ChildBg;
6272
108k
    return ImGuiCol_WindowBg;
6273
132k
}
6274
6275
static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size)
6276
0
{
6277
0
    ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm);                // Expected window upper-left
6278
0
    ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right
6279
0
    ImVec2 size_expected = pos_max - pos_min;
6280
0
    ImVec2 size_constrained = CalcWindowSizeAfterConstraint(window, size_expected);
6281
0
    *out_pos = pos_min;
6282
0
    if (corner_norm.x == 0.0f)
6283
0
        out_pos->x -= (size_constrained.x - size_expected.x);
6284
0
    if (corner_norm.y == 0.0f)
6285
0
        out_pos->y -= (size_constrained.y - size_expected.y);
6286
0
    *out_size = size_constrained;
6287
0
}
6288
6289
// Data for resizing from resize grip / corner
6290
struct ImGuiResizeGripDef
6291
{
6292
    ImVec2  CornerPosN;
6293
    ImVec2  InnerDir;
6294
    int     AngleMin12, AngleMax12;
6295
};
6296
static const ImGuiResizeGripDef resize_grip_def[4] =
6297
{
6298
    { ImVec2(1, 1), ImVec2(-1, -1), 0, 3 },  // Lower-right
6299
    { ImVec2(0, 1), ImVec2(+1, -1), 3, 6 },  // Lower-left
6300
    { ImVec2(0, 0), ImVec2(+1, +1), 6, 9 },  // Upper-left (Unused)
6301
    { ImVec2(1, 0), ImVec2(-1, +1), 9, 12 }  // Upper-right (Unused)
6302
};
6303
6304
// Data for resizing from borders
6305
struct ImGuiResizeBorderDef
6306
{
6307
    ImVec2  InnerDir;               // Normal toward inside
6308
    ImVec2  SegmentN1, SegmentN2;   // End positions, normalized (0,0: upper left)
6309
    float   OuterAngle;             // Angle toward outside
6310
};
6311
static const ImGuiResizeBorderDef resize_border_def[4] =
6312
{
6313
    { ImVec2(+1, 0), ImVec2(0, 1), ImVec2(0, 0), IM_PI * 1.00f }, // Left
6314
    { ImVec2(-1, 0), ImVec2(1, 0), ImVec2(1, 1), IM_PI * 0.00f }, // Right
6315
    { ImVec2(0, +1), ImVec2(0, 0), ImVec2(1, 0), IM_PI * 1.50f }, // Up
6316
    { ImVec2(0, -1), ImVec2(1, 1), ImVec2(0, 1), IM_PI * 0.50f }  // Down
6317
};
6318
6319
static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness)
6320
94.8k
{
6321
94.8k
    ImRect rect = window->Rect();
6322
94.8k
    if (thickness == 0.0f)
6323
0
        rect.Max -= ImVec2(1, 1);
6324
94.8k
    if (border_n == ImGuiDir_Left)  { return ImRect(rect.Min.x - thickness,    rect.Min.y + perp_padding, rect.Min.x + thickness,    rect.Max.y - perp_padding); }
6325
71.1k
    if (border_n == ImGuiDir_Right) { return ImRect(rect.Max.x - thickness,    rect.Min.y + perp_padding, rect.Max.x + thickness,    rect.Max.y - perp_padding); }
6326
47.4k
    if (border_n == ImGuiDir_Up)    { return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness,    rect.Max.x - perp_padding, rect.Min.y + thickness);    }
6327
23.7k
    if (border_n == ImGuiDir_Down)  { return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness,    rect.Max.x - perp_padding, rect.Max.y + thickness);    }
6328
0
    IM_ASSERT(0);
6329
0
    return ImRect();
6330
23.7k
}
6331
6332
// 0..3: corners (Lower-right, Lower-left, Unused, Unused)
6333
ImGuiID ImGui::GetWindowResizeCornerID(ImGuiWindow* window, int n)
6334
0
{
6335
0
    IM_ASSERT(n >= 0 && n < 4);
6336
0
    ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
6337
0
    id = ImHashStr("#RESIZE", 0, id);
6338
0
    id = ImHashData(&n, sizeof(int), id);
6339
0
    return id;
6340
0
}
6341
6342
// Borders (Left, Right, Up, Down)
6343
ImGuiID ImGui::GetWindowResizeBorderID(ImGuiWindow* window, ImGuiDir dir)
6344
0
{
6345
0
    IM_ASSERT(dir >= 0 && dir < 4);
6346
0
    int n = (int)dir + 4;
6347
0
    ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
6348
0
    id = ImHashStr("#RESIZE", 0, id);
6349
0
    id = ImHashData(&n, sizeof(int), id);
6350
0
    return id;
6351
0
}
6352
6353
// Handle resize for: Resize Grips, Borders, Gamepad
6354
// Return true when using auto-fit (double-click on resize grip)
6355
static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_hovered, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect)
6356
132k
{
6357
132k
    ImGuiContext& g = *GImGui;
6358
132k
    ImGuiWindowFlags flags = window->Flags;
6359
6360
132k
    if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
6361
23.7k
        return false;
6362
108k
    if (window->WasActive == false) // Early out to avoid running this code for e.g. a hidden implicit/fallback Debug window.
6363
84.9k
        return false;
6364
6365
23.7k
    int ret_auto_fit_mask = 0x00;
6366
23.7k
    const float grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
6367
23.7k
    const float grip_hover_inner_size = (resize_grip_count > 0) ? IM_TRUNC(grip_draw_size * 0.75f) : 0.0f;
6368
23.7k
    const float grip_hover_outer_size = g.IO.ConfigWindowsResizeFromEdges ? WINDOWS_HOVER_PADDING : 0.0f;
6369
6370
23.7k
    ImRect clamp_rect = visibility_rect;
6371
23.7k
    const bool window_move_from_title_bar = g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar);
6372
23.7k
    if (window_move_from_title_bar)
6373
0
        clamp_rect.Min.y -= window->TitleBarHeight;
6374
6375
23.7k
    ImVec2 pos_target(FLT_MAX, FLT_MAX);
6376
23.7k
    ImVec2 size_target(FLT_MAX, FLT_MAX);
6377
6378
    // Clip mouse interaction rectangles within the viewport rectangle (in practice the narrowing is going to happen most of the time).
6379
    // - Not narrowing would mostly benefit the situation where OS windows _without_ decoration have a threshold for hovering when outside their limits.
6380
    //   This is however not the case with current backends under Win32, but a custom borderless window implementation would benefit from it.
6381
    // - When decoration are enabled we typically benefit from that distance, but then our resize elements would be conflicting with OS resize elements, so we also narrow.
6382
    // - Note that we are unable to tell if the platform setup allows hovering with a distance threshold (on Win32, decorated window have such threshold).
6383
    // We only clip interaction so we overwrite window->ClipRect, cannot call PushClipRect() yet as DrawList is not yet setup.
6384
23.7k
    const bool clip_with_viewport_rect = !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport) || (g.IO.MouseHoveredViewport != window->ViewportId) || !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration);
6385
23.7k
    if (clip_with_viewport_rect)
6386
23.7k
        window->ClipRect = window->Viewport->GetMainRect();
6387
6388
    // Resize grips and borders are on layer 1
6389
23.7k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
6390
6391
    // Manual resize grips
6392
23.7k
    PushID("#RESIZE");
6393
71.1k
    for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
6394
47.4k
    {
6395
47.4k
        const ImGuiResizeGripDef& def = resize_grip_def[resize_grip_n];
6396
47.4k
        const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, def.CornerPosN);
6397
6398
        // Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
6399
47.4k
        bool hovered, held;
6400
47.4k
        ImRect resize_rect(corner - def.InnerDir * grip_hover_outer_size, corner + def.InnerDir * grip_hover_inner_size);
6401
47.4k
        if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(resize_rect.Min.x, resize_rect.Max.x);
6402
47.4k
        if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(resize_rect.Min.y, resize_rect.Max.y);
6403
47.4k
        ImGuiID resize_grip_id = window->GetID(resize_grip_n); // == GetWindowResizeCornerID()
6404
47.4k
        ItemAdd(resize_rect, resize_grip_id, NULL, ImGuiItemFlags_NoNav);
6405
47.4k
        ButtonBehavior(resize_rect, resize_grip_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
6406
        //GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255));
6407
47.4k
        if (hovered || held)
6408
0
            g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;
6409
6410
47.4k
        if (held && g.IO.MouseDoubleClicked[0])
6411
0
        {
6412
            // Auto-fit when double-clicking
6413
0
            size_target = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6414
0
            ret_auto_fit_mask = 0x03; // Both axises
6415
0
            ClearActiveID();
6416
0
        }
6417
47.4k
        else if (held)
6418
0
        {
6419
            // Resize from any of the four corners
6420
            // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
6421
0
            ImVec2 clamp_min = ImVec2(def.CornerPosN.x == 1.0f ? clamp_rect.Min.x : -FLT_MAX, (def.CornerPosN.y == 1.0f || (def.CornerPosN.y == 0.0f && window_move_from_title_bar)) ? clamp_rect.Min.y : -FLT_MAX);
6422
0
            ImVec2 clamp_max = ImVec2(def.CornerPosN.x == 0.0f ? clamp_rect.Max.x : +FLT_MAX, def.CornerPosN.y == 0.0f ? clamp_rect.Max.y : +FLT_MAX);
6423
0
            ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(def.InnerDir * grip_hover_outer_size, def.InnerDir * -grip_hover_inner_size, def.CornerPosN); // Corner of the window corresponding to our corner grip
6424
0
            corner_target = ImClamp(corner_target, clamp_min, clamp_max);
6425
0
            CalcResizePosSizeFromAnyCorner(window, corner_target, def.CornerPosN, &pos_target, &size_target);
6426
0
        }
6427
6428
        // Only lower-left grip is visible before hovering/activating
6429
47.4k
        if (resize_grip_n == 0 || held || hovered)
6430
23.7k
            resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
6431
47.4k
    }
6432
6433
23.7k
    int resize_border_mask = 0x00;
6434
23.7k
    if (window->Flags & ImGuiWindowFlags_ChildWindow)
6435
0
        resize_border_mask |= ((window->ChildFlags & ImGuiChildFlags_ResizeX) ? 0x02 : 0) | ((window->ChildFlags & ImGuiChildFlags_ResizeY) ? 0x08 : 0);
6436
23.7k
    else
6437
23.7k
        resize_border_mask = g.IO.ConfigWindowsResizeFromEdges ? 0x0F : 0x00;
6438
118k
    for (int border_n = 0; border_n < 4; border_n++)
6439
94.8k
    {
6440
94.8k
        if ((resize_border_mask & (1 << border_n)) == 0)
6441
0
            continue;
6442
94.8k
        const ImGuiResizeBorderDef& def = resize_border_def[border_n];
6443
94.8k
        const ImGuiAxis axis = (border_n == ImGuiDir_Left || border_n == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
6444
6445
94.8k
        bool hovered, held;
6446
94.8k
        ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, WINDOWS_HOVER_PADDING);
6447
94.8k
        ImGuiID border_id = window->GetID(border_n + 4); // == GetWindowResizeBorderID()
6448
94.8k
        ItemAdd(border_rect, border_id, NULL, ImGuiItemFlags_NoNav);
6449
94.8k
        ButtonBehavior(border_rect, border_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
6450
        //GetForegroundDrawList(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255));
6451
94.8k
        if (hovered && g.HoveredIdTimer <= WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER)
6452
0
            hovered = false;
6453
94.8k
        if (hovered || held)
6454
0
            g.MouseCursor = (axis == ImGuiAxis_X) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS;
6455
94.8k
        if (held && g.IO.MouseDoubleClicked[0])
6456
0
        {
6457
            // Double-clicking bottom or right border auto-fit on this axis
6458
            // FIXME: CalcWindowAutoFitSize() doesn't take into account that only one side may be auto-fit when calculating scrollbars.
6459
            // FIXME: Support top and right borders: rework CalcResizePosSizeFromAnyCorner() to be reusable in both cases.
6460
0
            if (border_n == 1 || border_n == 3) // Right and bottom border
6461
0
            {
6462
0
                size_target[axis] = CalcWindowSizeAfterConstraint(window, size_auto_fit)[axis];
6463
0
                ret_auto_fit_mask |= (1 << axis);
6464
0
                hovered = held = false; // So border doesn't show highlighted at new position
6465
0
            }
6466
0
            ClearActiveID();
6467
0
        }
6468
94.8k
        else if (held)
6469
0
        {
6470
            // Switch to relative resizing mode when border geometry moved (e.g. resizing a child altering parent scroll), in order to avoid resizing feedback loop.
6471
            // Currently only using relative mode on resizable child windows, as the problem to solve is more likely noticeable for them, but could apply for all windows eventually.
6472
            // FIXME: May want to generalize this idiom at lower-level, so more widgets can use it!
6473
0
            const bool just_scrolled_manually_while_resizing = (g.WheelingWindow != NULL && g.WheelingWindowScrolledFrame == g.FrameCount && IsWindowChildOf(window, g.WheelingWindow, false, true));
6474
0
            if (g.ActiveIdIsJustActivated || just_scrolled_manually_while_resizing)
6475
0
            {
6476
0
                g.WindowResizeBorderExpectedRect = border_rect;
6477
0
                g.WindowResizeRelativeMode = false;
6478
0
            }
6479
0
            if ((window->Flags & ImGuiWindowFlags_ChildWindow) && memcmp(&g.WindowResizeBorderExpectedRect, &border_rect, sizeof(ImRect)) != 0)
6480
0
                g.WindowResizeRelativeMode = true;
6481
6482
0
            const ImVec2 border_curr = (window->Pos + ImMin(def.SegmentN1, def.SegmentN2) * window->Size);
6483
0
            const float border_target_rel_mode_for_axis = border_curr[axis] + g.IO.MouseDelta[axis];
6484
0
            const float border_target_abs_mode_for_axis = g.IO.MousePos[axis] - g.ActiveIdClickOffset[axis] + WINDOWS_HOVER_PADDING; // Match ButtonBehavior() padding above.
6485
6486
            // Use absolute mode position
6487
0
            ImVec2 border_target = window->Pos;
6488
0
            border_target[axis] = border_target_abs_mode_for_axis;
6489
6490
            // Use relative mode target for child window, ignore resize when moving back toward the ideal absolute position.
6491
0
            bool ignore_resize = false;
6492
0
            if (g.WindowResizeRelativeMode)
6493
0
            {
6494
                //GetForegroundDrawList()->AddText(GetMainViewport()->WorkPos, IM_COL32_WHITE, "Relative Mode");
6495
0
                border_target[axis] = border_target_rel_mode_for_axis;
6496
0
                if (g.IO.MouseDelta[axis] == 0.0f || (g.IO.MouseDelta[axis] > 0.0f) == (border_target_rel_mode_for_axis > border_target_abs_mode_for_axis))
6497
0
                    ignore_resize = true;
6498
0
            }
6499
6500
            // Clamp, apply
6501
0
            ImVec2 clamp_min(border_n == ImGuiDir_Right ? clamp_rect.Min.x : -FLT_MAX, border_n == ImGuiDir_Down || (border_n == ImGuiDir_Up && window_move_from_title_bar) ? clamp_rect.Min.y : -FLT_MAX);
6502
0
            ImVec2 clamp_max(border_n == ImGuiDir_Left ? clamp_rect.Max.x : +FLT_MAX, border_n == ImGuiDir_Up ? clamp_rect.Max.y : +FLT_MAX);
6503
0
            border_target = ImClamp(border_target, clamp_min, clamp_max);
6504
0
            if (flags & ImGuiWindowFlags_ChildWindow) // Clamp resizing of childs within parent
6505
0
            {
6506
0
                ImGuiWindow* parent_window = window->ParentWindow;
6507
0
                ImGuiWindowFlags parent_flags = parent_window->Flags;
6508
0
                ImRect border_limit_rect = parent_window->InnerRect;
6509
0
                border_limit_rect.Expand(ImVec2(-ImMax(parent_window->WindowPadding.x, parent_window->WindowBorderSize), -ImMax(parent_window->WindowPadding.y, parent_window->WindowBorderSize)));
6510
0
                if ((axis == ImGuiAxis_X) && ((parent_flags & (ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar)) == 0 || (parent_flags & ImGuiWindowFlags_NoScrollbar)))
6511
0
                    border_target.x = ImClamp(border_target.x, border_limit_rect.Min.x, border_limit_rect.Max.x);
6512
0
                if ((axis == ImGuiAxis_Y) && (parent_flags & ImGuiWindowFlags_NoScrollbar))
6513
0
                    border_target.y = ImClamp(border_target.y, border_limit_rect.Min.y, border_limit_rect.Max.y);
6514
0
            }
6515
0
            if (!ignore_resize)
6516
0
                CalcResizePosSizeFromAnyCorner(window, border_target, ImMin(def.SegmentN1, def.SegmentN2), &pos_target, &size_target);
6517
0
        }
6518
94.8k
        if (hovered)
6519
0
            *border_hovered = border_n;
6520
94.8k
        if (held)
6521
0
            *border_held = border_n;
6522
94.8k
    }
6523
23.7k
    PopID();
6524
6525
    // Restore nav layer
6526
23.7k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
6527
6528
    // Navigation resize (keyboard/gamepad)
6529
    // FIXME: This cannot be moved to NavUpdateWindowing() because CalcWindowSizeAfterConstraint() need to callback into user.
6530
    // Not even sure the callback works here.
6531
23.7k
    if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindowDockTree == window)
6532
0
    {
6533
0
        ImVec2 nav_resize_dir;
6534
0
        if (g.NavInputSource == ImGuiInputSource_Keyboard && g.IO.KeyShift)
6535
0
            nav_resize_dir = GetKeyMagnitude2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
6536
0
        if (g.NavInputSource == ImGuiInputSource_Gamepad)
6537
0
            nav_resize_dir = GetKeyMagnitude2d(ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown);
6538
0
        if (nav_resize_dir.x != 0.0f || nav_resize_dir.y != 0.0f)
6539
0
        {
6540
0
            const float NAV_RESIZE_SPEED = 600.0f;
6541
0
            const float resize_step = NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y);
6542
0
            g.NavWindowingAccumDeltaSize += nav_resize_dir * resize_step;
6543
0
            g.NavWindowingAccumDeltaSize = ImMax(g.NavWindowingAccumDeltaSize, clamp_rect.Min - window->Pos - window->Size); // We need Pos+Size >= clmap_rect.Min, so Size >= clmap_rect.Min - Pos, so size_delta >= clmap_rect.Min - window->Pos - window->Size
6544
0
            g.NavWindowingToggleLayer = false;
6545
0
            g.NavDisableMouseHover = true;
6546
0
            resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive);
6547
0
            ImVec2 accum_floored = ImTrunc(g.NavWindowingAccumDeltaSize);
6548
0
            if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
6549
0
            {
6550
                // FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck.
6551
0
                size_target = CalcWindowSizeAfterConstraint(window, window->SizeFull + accum_floored);
6552
0
                g.NavWindowingAccumDeltaSize -= accum_floored;
6553
0
            }
6554
0
        }
6555
0
    }
6556
6557
    // Apply back modified position/size to window
6558
23.7k
    const ImVec2 curr_pos = window->Pos;
6559
23.7k
    const ImVec2 curr_size = window->SizeFull;
6560
23.7k
    if (size_target.x != FLT_MAX && (window->Size.x != size_target.x || window->SizeFull.x != size_target.x))
6561
0
        window->Size.x = window->SizeFull.x = size_target.x;
6562
23.7k
    if (size_target.y != FLT_MAX && (window->Size.y != size_target.y || window->SizeFull.y != size_target.y))
6563
0
        window->Size.y = window->SizeFull.y = size_target.y;
6564
23.7k
    if (pos_target.x != FLT_MAX && window->Pos.x != ImTrunc(pos_target.x))
6565
0
        window->Pos.x = ImTrunc(pos_target.x);
6566
23.7k
    if (pos_target.y != FLT_MAX && window->Pos.y != ImTrunc(pos_target.y))
6567
0
        window->Pos.y = ImTrunc(pos_target.y);
6568
23.7k
    if (curr_pos.x != window->Pos.x || curr_pos.y != window->Pos.y || curr_size.x != window->SizeFull.x || curr_size.y != window->SizeFull.y)
6569
0
        MarkIniSettingsDirty(window);
6570
6571
    // Recalculate next expected border expected coordinates
6572
23.7k
    if (*border_held != -1)
6573
0
        g.WindowResizeBorderExpectedRect = GetResizeBorderRect(window, *border_held, grip_hover_inner_size, WINDOWS_HOVER_PADDING);
6574
6575
23.7k
    return ret_auto_fit_mask;
6576
108k
}
6577
6578
static inline void ClampWindowPos(ImGuiWindow* window, const ImRect& visibility_rect)
6579
169k
{
6580
169k
    ImGuiContext& g = *GImGui;
6581
169k
    ImVec2 size_for_clamping = window->Size;
6582
169k
    if (g.IO.ConfigWindowsMoveFromTitleBarOnly && window->DockNodeAsHost)
6583
0
        size_for_clamping.y = ImGui::GetFrameHeight(); // Not using window->TitleBarHeight() as DockNodeAsHost will report 0.0f here.
6584
169k
    else if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar))
6585
0
        size_for_clamping.y = window->TitleBarHeight;
6586
169k
    window->Pos = ImClamp(window->Pos, visibility_rect.Min - size_for_clamping, visibility_rect.Max);
6587
169k
}
6588
6589
static void RenderWindowOuterSingleBorder(ImGuiWindow* window, int border_n, ImU32 border_col, float border_size)
6590
0
{
6591
0
    const ImGuiResizeBorderDef& def = resize_border_def[border_n];
6592
0
    const float rounding = window->WindowRounding;
6593
0
    const ImRect border_r = GetResizeBorderRect(window, border_n, rounding, 0.0f);
6594
0
    window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle - IM_PI * 0.25f, def.OuterAngle);
6595
0
    window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN2) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle, def.OuterAngle + IM_PI * 0.25f);
6596
0
    window->DrawList->PathStroke(border_col, ImDrawFlags_None, border_size);
6597
0
}
6598
6599
static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window)
6600
132k
{
6601
132k
    ImGuiContext& g = *GImGui;
6602
132k
    const float border_size = window->WindowBorderSize;
6603
132k
    const ImU32 border_col = GetColorU32(ImGuiCol_Border);
6604
132k
    if (border_size > 0.0f && (window->Flags & ImGuiWindowFlags_NoBackground) == 0)
6605
121k
        window->DrawList->AddRect(window->Pos, window->Pos + window->Size, border_col, window->WindowRounding, 0, window->WindowBorderSize);
6606
10.5k
    else if (border_size > 0.0f)
6607
0
    {
6608
0
        if (window->ChildFlags & ImGuiChildFlags_ResizeX) // Similar code as 'resize_border_mask' computation in UpdateWindowManualResize() but we specifically only always draw explicit child resize border.
6609
0
            RenderWindowOuterSingleBorder(window, 1, border_col, border_size);
6610
0
        if (window->ChildFlags & ImGuiChildFlags_ResizeY)
6611
0
            RenderWindowOuterSingleBorder(window, 3, border_col, border_size);
6612
0
    }
6613
132k
    if (window->ResizeBorderHovered != -1 || window->ResizeBorderHeld != -1)
6614
0
    {
6615
0
        const int border_n = (window->ResizeBorderHeld != -1) ? window->ResizeBorderHeld : window->ResizeBorderHovered;
6616
0
        const ImU32 border_col_resizing = GetColorU32((window->ResizeBorderHeld != -1) ? ImGuiCol_SeparatorActive : ImGuiCol_SeparatorHovered);
6617
0
        RenderWindowOuterSingleBorder(window, border_n, border_col_resizing, ImMax(2.0f, window->WindowBorderSize)); // Thicker than usual
6618
0
    }
6619
132k
    if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
6620
0
    {
6621
0
        float y = window->Pos.y + window->TitleBarHeight - 1;
6622
0
        window->DrawList->AddLine(ImVec2(window->Pos.x + border_size, y), ImVec2(window->Pos.x + window->Size.x - border_size, y), border_col, g.Style.FrameBorderSize);
6623
0
    }
6624
132k
}
6625
6626
// Draw background and borders
6627
// Draw and handle scrollbars
6628
void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size)
6629
193k
{
6630
193k
    ImGuiContext& g = *GImGui;
6631
193k
    ImGuiStyle& style = g.Style;
6632
193k
    ImGuiWindowFlags flags = window->Flags;
6633
6634
    // Ensure that ScrollBar doesn't read last frame's SkipItems
6635
193k
    IM_ASSERT(window->BeginCount == 0);
6636
193k
    window->SkipItems = false;
6637
6638
    // Draw window + handle manual resize
6639
    // As we highlight the title bar when want_focus is set, multiple reappearing windows will have their title bar highlighted on their reappearing frame.
6640
193k
    const float window_rounding = window->WindowRounding;
6641
193k
    const float window_border_size = window->WindowBorderSize;
6642
193k
    if (window->Collapsed)
6643
61.2k
    {
6644
        // Title bar only
6645
61.2k
        const float backup_border_size = style.FrameBorderSize;
6646
61.2k
        g.Style.FrameBorderSize = window->WindowBorderSize;
6647
61.2k
        ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed);
6648
61.2k
        if (window->ViewportOwned)
6649
0
            title_bar_col |= IM_COL32_A_MASK; // No alpha (we don't support is_docking_transparent_payload here because simpler and less meaningful, but could with a bit of code shuffle/reuse)
6650
61.2k
        RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding);
6651
61.2k
        g.Style.FrameBorderSize = backup_border_size;
6652
61.2k
    }
6653
132k
    else
6654
132k
    {
6655
        // Window background
6656
132k
        if (!(flags & ImGuiWindowFlags_NoBackground))
6657
132k
        {
6658
132k
            bool is_docking_transparent_payload = false;
6659
132k
            if (g.DragDropActive && (g.FrameCount - g.DragDropAcceptFrameCount) <= 1 && g.IO.ConfigDockingTransparentPayload)
6660
0
                if (g.DragDropPayload.IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && *(ImGuiWindow**)g.DragDropPayload.Data == window)
6661
0
                    is_docking_transparent_payload = true;
6662
6663
132k
            ImU32 bg_col = GetColorU32(GetWindowBgColorIdx(window));
6664
132k
            if (window->ViewportOwned)
6665
0
            {
6666
0
                bg_col |= IM_COL32_A_MASK; // No alpha
6667
0
                if (is_docking_transparent_payload)
6668
0
                    window->Viewport->Alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA;
6669
0
            }
6670
132k
            else
6671
132k
            {
6672
                // Adjust alpha. For docking
6673
132k
                bool override_alpha = false;
6674
132k
                float alpha = 1.0f;
6675
132k
                if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasBgAlpha)
6676
0
                {
6677
0
                    alpha = g.NextWindowData.BgAlphaVal;
6678
0
                    override_alpha = true;
6679
0
                }
6680
132k
                if (is_docking_transparent_payload)
6681
0
                {
6682
0
                    alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA; // FIXME-DOCK: Should that be an override?
6683
0
                    override_alpha = true;
6684
0
                }
6685
132k
                if (override_alpha)
6686
0
                    bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT);
6687
132k
            }
6688
6689
            // Render, for docked windows and host windows we ensure bg goes before decorations
6690
132k
            if (window->DockIsActive)
6691
0
                window->DockNode->LastBgColor = bg_col;
6692
132k
            ImDrawList* bg_draw_list = window->DockIsActive ? window->DockNode->HostWindow->DrawList : window->DrawList;
6693
132k
            if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
6694
0
                bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
6695
132k
            bg_draw_list->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? 0 : ImDrawFlags_RoundCornersBottom);
6696
132k
            if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
6697
0
                bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
6698
132k
        }
6699
132k
        if (window->DockIsActive)
6700
0
            window->DockNode->IsBgDrawnThisFrame = true;
6701
6702
        // Title bar
6703
        // (when docked, DockNode are drawing their own title bar. Individual windows however do NOT set the _NoTitleBar flag,
6704
        // in order for their pos/size to be matching their undocking state.)
6705
132k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
6706
108k
        {
6707
108k
            ImU32 title_bar_col = GetColorU32(title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
6708
108k
            if (window->ViewportOwned)
6709
0
                title_bar_col |= IM_COL32_A_MASK; // No alpha
6710
108k
            window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawFlags_RoundCornersTop);
6711
108k
        }
6712
6713
        // Menu bar
6714
132k
        if (flags & ImGuiWindowFlags_MenuBar)
6715
0
        {
6716
0
            ImRect menu_bar_rect = window->MenuBarRect();
6717
0
            menu_bar_rect.ClipWith(window->Rect());  // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them.
6718
0
            window->DrawList->AddRectFilled(menu_bar_rect.Min + ImVec2(window_border_size, 0), menu_bar_rect.Max - ImVec2(window_border_size, 0), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawFlags_RoundCornersTop);
6719
0
            if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y)
6720
0
                window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
6721
0
        }
6722
6723
        // Docking: Unhide tab bar (small triangle in the corner), drag from small triangle to quickly undock
6724
132k
        ImGuiDockNode* node = window->DockNode;
6725
132k
        if (window->DockIsActive && node->IsHiddenTabBar() && !node->IsNoTabBar())
6726
0
        {
6727
0
            float unhide_sz_draw = ImTrunc(g.FontSize * 0.70f);
6728
0
            float unhide_sz_hit = ImTrunc(g.FontSize * 0.55f);
6729
0
            ImVec2 p = node->Pos;
6730
0
            ImRect r(p, p + ImVec2(unhide_sz_hit, unhide_sz_hit));
6731
0
            ImGuiID unhide_id = window->GetID("#UNHIDE");
6732
0
            KeepAliveID(unhide_id);
6733
0
            bool hovered, held;
6734
0
            if (ButtonBehavior(r, unhide_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren))
6735
0
                node->WantHiddenTabBarToggle = true;
6736
0
            else if (held && IsMouseDragging(0))
6737
0
                StartMouseMovingWindowOrNode(window, node, true); // Undock from tab-bar triangle = same as window/collapse menu button
6738
6739
            // FIXME-DOCK: Ideally we'd use ImGuiCol_TitleBgActive/ImGuiCol_TitleBg here, but neither is guaranteed to be visible enough at this sort of size..
6740
0
            ImU32 col = GetColorU32(((held && hovered) || (node->IsFocused && !hovered)) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
6741
0
            window->DrawList->AddTriangleFilled(p, p + ImVec2(unhide_sz_draw, 0.0f), p + ImVec2(0.0f, unhide_sz_draw), col);
6742
0
        }
6743
6744
        // Scrollbars
6745
132k
        if (window->ScrollbarX)
6746
23.7k
            Scrollbar(ImGuiAxis_X);
6747
132k
        if (window->ScrollbarY)
6748
20.7k
            Scrollbar(ImGuiAxis_Y);
6749
6750
        // Render resize grips (after their input handling so we don't have a frame of latency)
6751
132k
        if (handle_borders_and_resize_grips && !(flags & ImGuiWindowFlags_NoResize))
6752
108k
        {
6753
326k
            for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
6754
217k
            {
6755
217k
                const ImU32 col = resize_grip_col[resize_grip_n];
6756
217k
                if ((col & IM_COL32_A_MASK) == 0)
6757
193k
                    continue;
6758
23.7k
                const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
6759
23.7k
                const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN);
6760
23.7k
                window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(window_border_size, resize_grip_draw_size) : ImVec2(resize_grip_draw_size, window_border_size)));
6761
23.7k
                window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(resize_grip_draw_size, window_border_size) : ImVec2(window_border_size, resize_grip_draw_size)));
6762
23.7k
                window->DrawList->PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + window_border_size), corner.y + grip.InnerDir.y * (window_rounding + window_border_size)), window_rounding, grip.AngleMin12, grip.AngleMax12);
6763
23.7k
                window->DrawList->PathFillConvex(col);
6764
23.7k
            }
6765
108k
        }
6766
6767
        // Borders (for dock node host they will be rendered over after the tab bar)
6768
132k
        if (handle_borders_and_resize_grips && !window->DockNodeAsHost)
6769
132k
            RenderWindowOuterBorders(window);
6770
132k
    }
6771
193k
}
6772
6773
// When inside a dock node, this is handled in DockNodeCalcTabBarLayout() instead.
6774
// Render title text, collapse button, close button
6775
void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open)
6776
169k
{
6777
169k
    ImGuiContext& g = *GImGui;
6778
169k
    ImGuiStyle& style = g.Style;
6779
169k
    ImGuiWindowFlags flags = window->Flags;
6780
6781
169k
    const bool has_close_button = (p_open != NULL);
6782
169k
    const bool has_collapse_button = !(flags & ImGuiWindowFlags_NoCollapse) && (style.WindowMenuButtonPosition != ImGuiDir_None);
6783
6784
    // Close & Collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer)
6785
    // FIXME-NAV: Might want (or not?) to set the equivalent of ImGuiButtonFlags_NoNavFocus so that mouse clicks on standard title bar items don't necessarily set nav/keyboard ref?
6786
169k
    const ImGuiItemFlags item_flags_backup = g.CurrentItemFlags;
6787
169k
    g.CurrentItemFlags |= ImGuiItemFlags_NoNavDefaultFocus;
6788
169k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
6789
6790
    // Layout buttons
6791
    // FIXME: Would be nice to generalize the subtleties expressed here into reusable code.
6792
169k
    float pad_l = style.FramePadding.x;
6793
169k
    float pad_r = style.FramePadding.x;
6794
169k
    float button_sz = g.FontSize;
6795
169k
    ImVec2 close_button_pos;
6796
169k
    ImVec2 collapse_button_pos;
6797
169k
    if (has_close_button)
6798
0
    {
6799
0
        close_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - button_sz, title_bar_rect.Min.y + style.FramePadding.y);
6800
0
        pad_r += button_sz + style.ItemInnerSpacing.x;
6801
0
    }
6802
169k
    if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Right)
6803
0
    {
6804
0
        collapse_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - button_sz, title_bar_rect.Min.y + style.FramePadding.y);
6805
0
        pad_r += button_sz + style.ItemInnerSpacing.x;
6806
0
    }
6807
169k
    if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Left)
6808
169k
    {
6809
169k
        collapse_button_pos = ImVec2(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y + style.FramePadding.y);
6810
169k
        pad_l += button_sz + style.ItemInnerSpacing.x;
6811
169k
    }
6812
6813
    // Collapse button (submitting first so it gets priority when choosing a navigation init fallback)
6814
169k
    if (has_collapse_button)
6815
169k
        if (CollapseButton(window->GetID("#COLLAPSE"), collapse_button_pos, NULL))
6816
1
            window->WantCollapseToggle = true; // Defer actual collapsing to next frame as we are too far in the Begin() function
6817
6818
    // Close button
6819
169k
    if (has_close_button)
6820
0
        if (CloseButton(window->GetID("#CLOSE"), close_button_pos))
6821
0
            *p_open = false;
6822
6823
169k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
6824
169k
    g.CurrentItemFlags = item_flags_backup;
6825
6826
    // Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker)
6827
    // FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code..
6828
169k
    const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? button_sz * 0.80f : 0.0f;
6829
169k
    const ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f);
6830
6831
    // As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button,
6832
    // while uncentered title text will still reach edges correctly.
6833
169k
    if (pad_l > style.FramePadding.x)
6834
169k
        pad_l += g.Style.ItemInnerSpacing.x;
6835
169k
    if (pad_r > style.FramePadding.x)
6836
0
        pad_r += g.Style.ItemInnerSpacing.x;
6837
169k
    if (style.WindowTitleAlign.x > 0.0f && style.WindowTitleAlign.x < 1.0f)
6838
0
    {
6839
0
        float centerness = ImSaturate(1.0f - ImFabs(style.WindowTitleAlign.x - 0.5f) * 2.0f); // 0.0f on either edges, 1.0f on center
6840
0
        float pad_extend = ImMin(ImMax(pad_l, pad_r), title_bar_rect.GetWidth() - pad_l - pad_r - text_size.x);
6841
0
        pad_l = ImMax(pad_l, pad_extend * centerness);
6842
0
        pad_r = ImMax(pad_r, pad_extend * centerness);
6843
0
    }
6844
6845
169k
    ImRect layout_r(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y, title_bar_rect.Max.x - pad_r, title_bar_rect.Max.y);
6846
169k
    ImRect clip_r(layout_r.Min.x, layout_r.Min.y, ImMin(layout_r.Max.x + g.Style.ItemInnerSpacing.x, title_bar_rect.Max.x), layout_r.Max.y);
6847
169k
    if (flags & ImGuiWindowFlags_UnsavedDocument)
6848
0
    {
6849
0
        ImVec2 marker_pos;
6850
0
        marker_pos.x = ImClamp(layout_r.Min.x + (layout_r.GetWidth() - text_size.x) * style.WindowTitleAlign.x + text_size.x, layout_r.Min.x, layout_r.Max.x);
6851
0
        marker_pos.y = (layout_r.Min.y + layout_r.Max.y) * 0.5f;
6852
0
        if (marker_pos.x > layout_r.Min.x)
6853
0
        {
6854
0
            RenderBullet(window->DrawList, marker_pos, GetColorU32(ImGuiCol_Text));
6855
0
            clip_r.Max.x = ImMin(clip_r.Max.x, marker_pos.x - (int)(marker_size_x * 0.5f));
6856
0
        }
6857
0
    }
6858
    //if (g.IO.KeyShift) window->DrawList->AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
6859
    //if (g.IO.KeyCtrl) window->DrawList->AddRect(clip_r.Min, clip_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
6860
169k
    RenderTextClipped(layout_r.Min, layout_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_r);
6861
169k
}
6862
6863
void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window)
6864
193k
{
6865
193k
    window->ParentWindow = parent_window;
6866
193k
    window->RootWindow = window->RootWindowPopupTree = window->RootWindowDockTree = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window;
6867
193k
    if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
6868
23.7k
    {
6869
23.7k
        window->RootWindowDockTree = parent_window->RootWindowDockTree;
6870
23.7k
        if (!window->DockIsActive && !(parent_window->Flags & ImGuiWindowFlags_DockNodeHost))
6871
23.7k
            window->RootWindow = parent_window->RootWindow;
6872
23.7k
    }
6873
193k
    if (parent_window && (flags & ImGuiWindowFlags_Popup))
6874
0
        window->RootWindowPopupTree = parent_window->RootWindowPopupTree;
6875
193k
    if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup))) // FIXME: simply use _NoTitleBar ?
6876
23.7k
        window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight;
6877
193k
    while (window->RootWindowForNav->ChildFlags & ImGuiChildFlags_NavFlattened)
6878
0
    {
6879
0
        IM_ASSERT(window->RootWindowForNav->ParentWindow != NULL);
6880
0
        window->RootWindowForNav = window->RootWindowForNav->ParentWindow;
6881
0
    }
6882
193k
}
6883
6884
// [EXPERIMENTAL] Called by Begin(). NextWindowData is valid at this point.
6885
// This is designed as a toy/test-bed for
6886
void ImGui::UpdateWindowSkipRefresh(ImGuiWindow* window)
6887
193k
{
6888
193k
    ImGuiContext& g = *GImGui;
6889
193k
    window->SkipRefresh = false;
6890
193k
    if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasRefreshPolicy) == 0)
6891
193k
        return;
6892
0
    if (g.NextWindowData.RefreshFlagsVal & ImGuiWindowRefreshFlags_TryToAvoidRefresh)
6893
0
    {
6894
        // FIXME-IDLE: Tests for e.g. mouse clicks or keyboard while focused.
6895
0
        if (window->Appearing) // If currently appearing
6896
0
            return;
6897
0
        if (window->Hidden) // If was hidden (previous frame)
6898
0
            return;
6899
0
        if ((g.NextWindowData.RefreshFlagsVal & ImGuiWindowRefreshFlags_RefreshOnHover) && g.HoveredWindow && window->RootWindow == g.HoveredWindow->RootWindow)
6900
0
            return;
6901
0
        if ((g.NextWindowData.RefreshFlagsVal & ImGuiWindowRefreshFlags_RefreshOnFocus) && g.NavWindow && window->RootWindow == g.NavWindow->RootWindow)
6902
0
            return;
6903
0
        window->DrawList = NULL;
6904
0
        window->SkipRefresh = true;
6905
0
    }
6906
0
}
6907
6908
// When a modal popup is open, newly created windows that want focus (i.e. are not popups and do not specify ImGuiWindowFlags_NoFocusOnAppearing)
6909
// should be positioned behind that modal window, unless the window was created inside the modal begin-stack.
6910
// In case of multiple stacked modals newly created window honors begin stack order and does not go below its own modal parent.
6911
// - WindowA            // FindBlockingModal() returns Modal1
6912
//   - WindowB          //                  .. returns Modal1
6913
//   - Modal1           //                  .. returns Modal2
6914
//      - WindowC       //                  .. returns Modal2
6915
//          - WindowD   //                  .. returns Modal2
6916
//          - Modal2    //                  .. returns Modal2
6917
//            - WindowE //                  .. returns NULL
6918
// Notes:
6919
// - FindBlockingModal(NULL) == NULL is generally equivalent to GetTopMostPopupModal() == NULL.
6920
//   Only difference is here we check for ->Active/WasActive but it may be unnecessary.
6921
ImGuiWindow* ImGui::FindBlockingModal(ImGuiWindow* window)
6922
30
{
6923
30
    ImGuiContext& g = *GImGui;
6924
30
    if (g.OpenPopupStack.Size <= 0)
6925
30
        return NULL;
6926
6927
    // Find a modal that has common parent with specified window. Specified window should be positioned behind that modal.
6928
0
    for (ImGuiPopupData& popup_data : g.OpenPopupStack)
6929
0
    {
6930
0
        ImGuiWindow* popup_window = popup_data.Window;
6931
0
        if (popup_window == NULL || !(popup_window->Flags & ImGuiWindowFlags_Modal))
6932
0
            continue;
6933
0
        if (!popup_window->Active && !popup_window->WasActive)      // Check WasActive, because this code may run before popup renders on current frame, also check Active to handle newly created windows.
6934
0
            continue;
6935
0
        if (window == NULL)                                         // FindBlockingModal(NULL) test for if FocusWindow(NULL) is naturally possible via a mouse click.
6936
0
            return popup_window;
6937
0
        if (IsWindowWithinBeginStackOf(window, popup_window))       // Window may be over modal
6938
0
            continue;
6939
0
        return popup_window;                                        // Place window right below first block modal
6940
0
    }
6941
0
    return NULL;
6942
0
}
6943
6944
// Push a new Dear ImGui window to add widgets to.
6945
// - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair.
6946
// - Begin/End can be called multiple times during the frame with the same window name to append content.
6947
// - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).
6948
//   You can use the "##" or "###" markers to use the same label with different id, or same id with different label. See documentation at the top of this file.
6949
// - Return false when window is collapsed, so you can early out in your code. You always need to call ImGui::End() even if false is returned.
6950
// - Passing 'bool* p_open' displays a Close button on the upper-right corner of the window, the pointed value will be set to false when the button is pressed.
6951
bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
6952
193k
{
6953
193k
    ImGuiContext& g = *GImGui;
6954
193k
    const ImGuiStyle& style = g.Style;
6955
193k
    IM_ASSERT(name != NULL && name[0] != '\0');     // Window name required
6956
193k
    IM_ASSERT(g.WithinFrameScope);                  // Forgot to call ImGui::NewFrame()
6957
193k
    IM_ASSERT(g.FrameCountEnded != g.FrameCount);   // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
6958
6959
    // Find or create
6960
193k
    ImGuiWindow* window = FindWindowByName(name);
6961
193k
    const bool window_just_created = (window == NULL);
6962
193k
    if (window_just_created)
6963
3
        window = CreateNewWindow(name, flags);
6964
6965
    // [DEBUG] Debug break requested by user
6966
193k
    if (g.DebugBreakInWindow == window->ID)
6967
0
        IM_DEBUG_BREAK();
6968
6969
    // Automatically disable manual moving/resizing when NoInputs is set
6970
193k
    if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs)
6971
0
        flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
6972
6973
193k
    const int current_frame = g.FrameCount;
6974
193k
    const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
6975
193k
    window->IsFallbackWindow = (g.CurrentWindowStack.Size == 0 && g.WithinFrameScopeWithImplicitWindow);
6976
6977
    // Update the Appearing flag (note: the BeginDocked() path may also set this to true later)
6978
193k
    bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
6979
193k
    if (flags & ImGuiWindowFlags_Popup)
6980
0
    {
6981
0
        ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
6982
0
        window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed
6983
0
        window_just_activated_by_user |= (window != popup_ref.Window);
6984
0
    }
6985
6986
    // Update Flags, LastFrameActive, BeginOrderXXX fields
6987
193k
    const bool window_was_appearing = window->Appearing;
6988
193k
    if (first_begin_of_the_frame)
6989
193k
    {
6990
193k
        UpdateWindowInFocusOrderList(window, window_just_created, flags);
6991
193k
        window->Appearing = window_just_activated_by_user;
6992
193k
        if (window->Appearing)
6993
3
            SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
6994
193k
        window->FlagsPreviousFrame = window->Flags;
6995
193k
        window->Flags = (ImGuiWindowFlags)flags;
6996
193k
        window->ChildFlags = (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasChildFlags) ? g.NextWindowData.ChildFlags : 0;
6997
193k
        window->LastFrameActive = current_frame;
6998
193k
        window->LastTimeActive = (float)g.Time;
6999
193k
        window->BeginOrderWithinParent = 0;
7000
193k
        window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++);
7001
193k
    }
7002
0
    else
7003
0
    {
7004
0
        flags = window->Flags;
7005
0
    }
7006
7007
    // Docking
7008
    // (NB: during the frame dock nodes are created, it is possible that (window->DockIsActive == false) even though (window->DockNode->Windows.Size > 1)
7009
193k
    IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL); // Cannot be both
7010
193k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasDock)
7011
0
        SetWindowDock(window, g.NextWindowData.DockId, g.NextWindowData.DockCond);
7012
193k
    if (first_begin_of_the_frame)
7013
193k
    {
7014
193k
        bool has_dock_node = (window->DockId != 0 || window->DockNode != NULL);
7015
193k
        bool new_auto_dock_node = !has_dock_node && GetWindowAlwaysWantOwnTabBar(window);
7016
193k
        bool dock_node_was_visible = window->DockNodeIsVisible;
7017
193k
        bool dock_tab_was_visible = window->DockTabIsVisible;
7018
193k
        if (has_dock_node || new_auto_dock_node)
7019
0
        {
7020
0
            BeginDocked(window, p_open);
7021
0
            flags = window->Flags;
7022
0
            if (window->DockIsActive)
7023
0
            {
7024
0
                IM_ASSERT(window->DockNode != NULL);
7025
0
                g.NextWindowData.Flags &= ~ImGuiNextWindowDataFlags_HasSizeConstraint; // Docking currently override constraints
7026
0
            }
7027
7028
            // Amend the Appearing flag
7029
0
            if (window->DockTabIsVisible && !dock_tab_was_visible && dock_node_was_visible && !window->Appearing && !window_was_appearing)
7030
0
            {
7031
0
                window->Appearing = true;
7032
0
                SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
7033
0
            }
7034
0
        }
7035
193k
        else
7036
193k
        {
7037
193k
            window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
7038
193k
        }
7039
193k
    }
7040
7041
    // Parent window is latched only on the first call to Begin() of the frame, so further append-calls can be done from a different window stack
7042
193k
    ImGuiWindow* parent_window_in_stack = (window->DockIsActive && window->DockNode->HostWindow) ? window->DockNode->HostWindow : g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back().Window;
7043
193k
    ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow;
7044
193k
    IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
7045
7046
    // We allow window memory to be compacted so recreate the base stack when needed.
7047
193k
    if (window->IDStack.Size == 0)
7048
0
        window->IDStack.push_back(window->ID);
7049
7050
    // Add to stack
7051
193k
    g.CurrentWindow = window;
7052
193k
    ImGuiWindowStackData window_stack_data;
7053
193k
    window_stack_data.Window = window;
7054
193k
    window_stack_data.ParentLastItemDataBackup = g.LastItemData;
7055
193k
    window_stack_data.StackSizesOnBegin.SetToContextState(&g);
7056
193k
    window_stack_data.DisabledOverrideReenable = (flags & ImGuiWindowFlags_Tooltip) && (g.CurrentItemFlags & ImGuiItemFlags_Disabled);
7057
193k
    g.CurrentWindowStack.push_back(window_stack_data);
7058
193k
    if (flags & ImGuiWindowFlags_ChildMenu)
7059
0
        g.BeginMenuDepth++;
7060
7061
    // Update ->RootWindow and others pointers (before any possible call to FocusWindow)
7062
193k
    if (first_begin_of_the_frame)
7063
193k
    {
7064
193k
        UpdateWindowParentAndRootLinks(window, flags, parent_window);
7065
193k
        window->ParentWindowInBeginStack = parent_window_in_stack;
7066
7067
        // Focus route
7068
        // There's little point to expose a flag to set this: because the interesting cases won't be using parent_window_in_stack,
7069
        // Use for e.g. linking a tool window in a standalone viewport to a document window, regardless of their Begin() stack parenting. (#6798)
7070
193k
        window->ParentWindowForFocusRoute = (window->RootWindow != window) ? parent_window_in_stack : NULL;
7071
193k
        if (window->ParentWindowForFocusRoute == NULL && window->DockNode != NULL)
7072
0
            if (window->DockNode->MergedFlags & ImGuiDockNodeFlags_DockedWindowsInFocusRoute)
7073
0
                window->ParentWindowForFocusRoute = window->DockNode->HostWindow;
7074
7075
        // Override with SetNextWindowClass() field or direct call to SetWindowParentWindowForFocusRoute()
7076
193k
        if (window->WindowClass.FocusRouteParentWindowId != 0)
7077
0
        {
7078
0
            window->ParentWindowForFocusRoute = FindWindowByID(window->WindowClass.FocusRouteParentWindowId);
7079
0
            IM_ASSERT(window->ParentWindowForFocusRoute != 0); // Invalid value for FocusRouteParentWindowId.
7080
0
        }
7081
193k
    }
7082
7083
    // Add to focus scope stack
7084
193k
    PushFocusScope((window->ChildFlags & ImGuiChildFlags_NavFlattened) ? g.CurrentFocusScopeId : window->ID);
7085
193k
    window->NavRootFocusScopeId = g.CurrentFocusScopeId;
7086
7087
    // Add to popup stacks: update OpenPopupStack[] data, push to BeginPopupStack[]
7088
193k
    if (flags & ImGuiWindowFlags_Popup)
7089
0
    {
7090
0
        ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
7091
0
        popup_ref.Window = window;
7092
0
        popup_ref.ParentNavLayer = parent_window_in_stack->DC.NavLayerCurrent;
7093
0
        g.BeginPopupStack.push_back(popup_ref);
7094
0
        window->PopupId = popup_ref.PopupId;
7095
0
    }
7096
7097
    // Process SetNextWindow***() calls
7098
    // (FIXME: Consider splitting the HasXXX flags into X/Y components
7099
193k
    bool window_pos_set_by_api = false;
7100
193k
    bool window_size_x_set_by_api = false, window_size_y_set_by_api = false;
7101
193k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos)
7102
0
    {
7103
0
        window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0;
7104
0
        if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f)
7105
0
        {
7106
            // May be processed on the next frame if this is our first frame and we are measuring size
7107
            // FIXME: Look into removing the branch so everything can go through this same code path for consistency.
7108
0
            window->SetWindowPosVal = g.NextWindowData.PosVal;
7109
0
            window->SetWindowPosPivot = g.NextWindowData.PosPivotVal;
7110
0
            window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
7111
0
        }
7112
0
        else
7113
0
        {
7114
0
            SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond);
7115
0
        }
7116
0
    }
7117
193k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize)
7118
108k
    {
7119
108k
        window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f);
7120
108k
        window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);
7121
108k
        if ((window->ChildFlags & ImGuiChildFlags_ResizeX) && (window->SetWindowSizeAllowFlags & ImGuiCond_FirstUseEver) == 0) // Axis-specific conditions for BeginChild()
7122
0
            g.NextWindowData.SizeVal.x = window->SizeFull.x;
7123
108k
        if ((window->ChildFlags & ImGuiChildFlags_ResizeY) && (window->SetWindowSizeAllowFlags & ImGuiCond_FirstUseEver) == 0)
7124
0
            g.NextWindowData.SizeVal.y = window->SizeFull.y;
7125
108k
        SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond);
7126
108k
    }
7127
193k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasScroll)
7128
0
    {
7129
0
        if (g.NextWindowData.ScrollVal.x >= 0.0f)
7130
0
        {
7131
0
            window->ScrollTarget.x = g.NextWindowData.ScrollVal.x;
7132
0
            window->ScrollTargetCenterRatio.x = 0.0f;
7133
0
        }
7134
0
        if (g.NextWindowData.ScrollVal.y >= 0.0f)
7135
0
        {
7136
0
            window->ScrollTarget.y = g.NextWindowData.ScrollVal.y;
7137
0
            window->ScrollTargetCenterRatio.y = 0.0f;
7138
0
        }
7139
0
    }
7140
193k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasContentSize)
7141
0
        window->ContentSizeExplicit = g.NextWindowData.ContentSizeVal;
7142
193k
    else if (first_begin_of_the_frame)
7143
193k
        window->ContentSizeExplicit = ImVec2(0.0f, 0.0f);
7144
193k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasWindowClass)
7145
0
        window->WindowClass = g.NextWindowData.WindowClass;
7146
193k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasCollapsed)
7147
0
        SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond);
7148
193k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasFocus)
7149
0
        FocusWindow(window);
7150
193k
    if (window->Appearing)
7151
3
        SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false);
7152
7153
    // [EXPERIMENTAL] Skip Refresh mode
7154
193k
    UpdateWindowSkipRefresh(window);
7155
7156
    // Nested root windows (typically tooltips) override disabled state
7157
193k
    if (window_stack_data.DisabledOverrideReenable && window->RootWindow == window)
7158
0
        BeginDisabledOverrideReenable();
7159
7160
    // We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow()
7161
193k
    g.CurrentWindow = NULL;
7162
7163
    // When reusing window again multiple times a frame, just append content (don't need to setup again)
7164
193k
    if (first_begin_of_the_frame && !window->SkipRefresh)
7165
193k
    {
7166
        // Initialize
7167
193k
        const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)
7168
193k
        const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesCannotSkipItems > 0);
7169
193k
        window->Active = true;
7170
193k
        window->HasCloseButton = (p_open != NULL);
7171
193k
        window->ClipRect = ImVec4(-FLT_MAX, -FLT_MAX, +FLT_MAX, +FLT_MAX);
7172
193k
        window->IDStack.resize(1);
7173
193k
        window->DrawList->_ResetForNewFrame();
7174
193k
        window->DC.CurrentTableIdx = -1;
7175
193k
        if (flags & ImGuiWindowFlags_DockNodeHost)
7176
0
        {
7177
0
            window->DrawList->ChannelsSplit(2);
7178
0
            window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG); // Render decorations on channel 1 as we will render the backgrounds manually later
7179
0
        }
7180
7181
        // Restore buffer capacity when woken from a compacted state, to avoid
7182
193k
        if (window->MemoryCompacted)
7183
0
            GcAwakeTransientWindowBuffers(window);
7184
7185
        // Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged).
7186
        // The title bar always display the 'name' parameter, so we only update the string storage if it needs to be visible to the end-user elsewhere.
7187
193k
        bool window_title_visible_elsewhere = false;
7188
193k
        if ((window->Viewport && window->Viewport->Window == window) || (window->DockIsActive))
7189
0
            window_title_visible_elsewhere = true;
7190
193k
        else if (g.NavWindowingListWindow != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0)   // Window titles visible when using CTRL+TAB
7191
0
            window_title_visible_elsewhere = true;
7192
193k
        if (window_title_visible_elsewhere && !window_just_created && strcmp(name, window->Name) != 0)
7193
0
        {
7194
0
            size_t buf_len = (size_t)window->NameBufLen;
7195
0
            window->Name = ImStrdupcpy(window->Name, &buf_len, name);
7196
0
            window->NameBufLen = (int)buf_len;
7197
0
        }
7198
7199
        // UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS
7200
7201
        // Update contents size from last frame for auto-fitting (or use explicit size)
7202
193k
        CalcWindowContentSizes(window, &window->ContentSize, &window->ContentSizeIdeal);
7203
7204
        // FIXME: These flags are decremented before they are used. This means that in order to have these fields produce their intended behaviors
7205
        // for one frame we must set them to at least 2, which is counter-intuitive. HiddenFramesCannotSkipItems is a more complicated case because
7206
        // it has a single usage before this code block and may be set below before it is finally checked.
7207
193k
        if (window->HiddenFramesCanSkipItems > 0)
7208
0
            window->HiddenFramesCanSkipItems--;
7209
193k
        if (window->HiddenFramesCannotSkipItems > 0)
7210
2
            window->HiddenFramesCannotSkipItems--;
7211
193k
        if (window->HiddenFramesForRenderOnly > 0)
7212
0
            window->HiddenFramesForRenderOnly--;
7213
7214
        // Hide new windows for one frame until they calculate their size
7215
193k
        if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api))
7216
1
            window->HiddenFramesCannotSkipItems = 1;
7217
7218
        // Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)
7219
        // We reset Size/ContentSize for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size.
7220
193k
        if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0)
7221
0
        {
7222
0
            window->HiddenFramesCannotSkipItems = 1;
7223
0
            if (flags & ImGuiWindowFlags_AlwaysAutoResize)
7224
0
            {
7225
0
                if (!window_size_x_set_by_api)
7226
0
                    window->Size.x = window->SizeFull.x = 0.f;
7227
0
                if (!window_size_y_set_by_api)
7228
0
                    window->Size.y = window->SizeFull.y = 0.f;
7229
0
                window->ContentSize = window->ContentSizeIdeal = ImVec2(0.f, 0.f);
7230
0
            }
7231
0
        }
7232
7233
        // SELECT VIEWPORT
7234
        // We need to do this before using any style/font sizes, as viewport with a different DPI may affect font sizes.
7235
7236
193k
        WindowSelectViewport(window);
7237
193k
        SetCurrentViewport(window, window->Viewport);
7238
193k
        window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
7239
193k
        SetCurrentWindow(window);
7240
193k
        flags = window->Flags;
7241
7242
        // LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies)
7243
        // We read Style data after the call to UpdateSelectWindowViewport() which might be swapping the style.
7244
7245
193k
        if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow))
7246
23.7k
            window->WindowBorderSize = style.ChildBorderSize;
7247
169k
        else
7248
169k
            window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
7249
193k
        window->WindowPadding = style.WindowPadding;
7250
193k
        if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !(window->ChildFlags & ImGuiChildFlags_AlwaysUseWindowPadding) && window->WindowBorderSize == 0.0f)
7251
10.5k
            window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f);
7252
7253
        // Lock menu offset so size calculation can use it as menu-bar windows need a minimum size.
7254
193k
        window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x);
7255
193k
        window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y;
7256
193k
        window->TitleBarHeight = (flags & ImGuiWindowFlags_NoTitleBar) ? 0.0f : g.FontSize + g.Style.FramePadding.y * 2.0f;
7257
193k
        window->MenuBarHeight = (flags & ImGuiWindowFlags_MenuBar) ? window->DC.MenuBarOffset.y + g.FontSize + g.Style.FramePadding.y * 2.0f : 0.0f;
7258
7259
        // Depending on condition we use previous or current window size to compare against contents size to decide if a scrollbar should be visible.
7260
        // Those flags will be altered further down in the function depending on more conditions.
7261
193k
        bool use_current_size_for_scrollbar_x = window_just_created;
7262
193k
        bool use_current_size_for_scrollbar_y = window_just_created;
7263
193k
        if (window_size_x_set_by_api && window->ContentSizeExplicit.x != 0.0f)
7264
0
            use_current_size_for_scrollbar_x = true;
7265
193k
        if (window_size_y_set_by_api && window->ContentSizeExplicit.y != 0.0f) // #7252
7266
0
            use_current_size_for_scrollbar_y = true;
7267
7268
        // Collapse window by double-clicking on title bar
7269
        // At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing
7270
193k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse) && !window->DockIsActive)
7271
169k
        {
7272
            // We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed), so verify that we don't have items over the title bar.
7273
169k
            ImRect title_bar_rect = window->TitleBarRect();
7274
169k
            if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max))
7275
40
                if (g.IO.MouseClickedCount[0] == 2 && GetKeyOwner(ImGuiKey_MouseLeft) == ImGuiKeyOwner_NoOwner)
7276
0
                    window->WantCollapseToggle = true;
7277
169k
            if (window->WantCollapseToggle)
7278
1
            {
7279
1
                window->Collapsed = !window->Collapsed;
7280
1
                if (!window->Collapsed)
7281
0
                    use_current_size_for_scrollbar_y = true;
7282
1
                MarkIniSettingsDirty(window);
7283
1
            }
7284
169k
        }
7285
23.7k
        else
7286
23.7k
        {
7287
23.7k
            window->Collapsed = false;
7288
23.7k
        }
7289
193k
        window->WantCollapseToggle = false;
7290
7291
        // SIZE
7292
7293
        // Outer Decoration Sizes
7294
        // (we need to clear ScrollbarSize immediately as CalcWindowAutoFitSize() needs it and can be called from other locations).
7295
193k
        const ImVec2 scrollbar_sizes_from_last_frame = window->ScrollbarSizes;
7296
193k
        window->DecoOuterSizeX1 = 0.0f;
7297
193k
        window->DecoOuterSizeX2 = 0.0f;
7298
193k
        window->DecoOuterSizeY1 = window->TitleBarHeight + window->MenuBarHeight;
7299
193k
        window->DecoOuterSizeY2 = 0.0f;
7300
193k
        window->ScrollbarSizes = ImVec2(0.0f, 0.0f);
7301
7302
        // Calculate auto-fit size, handle automatic resize
7303
193k
        const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSizeIdeal);
7304
193k
        if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed)
7305
0
        {
7306
            // Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc.
7307
0
            if (!window_size_x_set_by_api)
7308
0
            {
7309
0
                window->SizeFull.x = size_auto_fit.x;
7310
0
                use_current_size_for_scrollbar_x = true;
7311
0
            }
7312
0
            if (!window_size_y_set_by_api)
7313
0
            {
7314
0
                window->SizeFull.y = size_auto_fit.y;
7315
0
                use_current_size_for_scrollbar_y = true;
7316
0
            }
7317
0
        }
7318
193k
        else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
7319
2
        {
7320
            // Auto-fit may only grow window during the first few frames
7321
            // We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
7322
2
            if (!window_size_x_set_by_api && window->AutoFitFramesX > 0)
7323
2
            {
7324
2
                window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
7325
2
                use_current_size_for_scrollbar_x = true;
7326
2
            }
7327
2
            if (!window_size_y_set_by_api && window->AutoFitFramesY > 0)
7328
2
            {
7329
2
                window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
7330
2
                use_current_size_for_scrollbar_y = true;
7331
2
            }
7332
2
            if (!window->Collapsed)
7333
2
                MarkIniSettingsDirty(window);
7334
2
        }
7335
7336
        // Apply minimum/maximum window size constraints and final size
7337
193k
        window->SizeFull = CalcWindowSizeAfterConstraint(window, window->SizeFull);
7338
193k
        window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull;
7339
7340
        // POSITION
7341
7342
        // Popup latch its initial position, will position itself when it appears next frame
7343
193k
        if (window_just_activated_by_user)
7344
3
        {
7345
3
            window->AutoPosLastDirection = ImGuiDir_None;
7346
3
            if ((flags & ImGuiWindowFlags_Popup) != 0 && !(flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api) // FIXME: BeginPopup() could use SetNextWindowPos()
7347
0
                window->Pos = g.BeginPopupStack.back().OpenPopupPos;
7348
3
        }
7349
7350
        // Position child window
7351
193k
        if (flags & ImGuiWindowFlags_ChildWindow)
7352
23.7k
        {
7353
23.7k
            IM_ASSERT(parent_window && parent_window->Active);
7354
23.7k
            window->BeginOrderWithinParent = (short)parent_window->DC.ChildWindows.Size;
7355
23.7k
            parent_window->DC.ChildWindows.push_back(window);
7356
23.7k
            if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip)
7357
23.7k
                window->Pos = parent_window->DC.CursorPos;
7358
23.7k
        }
7359
7360
193k
        const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0);
7361
193k
        if (window_pos_with_pivot)
7362
0
            SetWindowPos(window, window->SetWindowPosVal - window->Size * window->SetWindowPosPivot, 0); // Position given a pivot (e.g. for centering)
7363
193k
        else if ((flags & ImGuiWindowFlags_ChildMenu) != 0)
7364
0
            window->Pos = FindBestWindowPosForPopup(window);
7365
193k
        else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize)
7366
0
            window->Pos = FindBestWindowPosForPopup(window);
7367
193k
        else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)
7368
0
            window->Pos = FindBestWindowPosForPopup(window);
7369
7370
        // Late create viewport if we don't fit within our current host viewport.
7371
193k
        if (window->ViewportAllowPlatformMonitorExtend >= 0 && !window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_IsMinimized))
7372
0
            if (!window->Viewport->GetMainRect().Contains(window->Rect()))
7373
0
            {
7374
                // This is based on the assumption that the DPI will be known ahead (same as the DPI of the selection done in UpdateSelectWindowViewport)
7375
                //ImGuiViewport* old_viewport = window->Viewport;
7376
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
7377
7378
                // FIXME-DPI
7379
                //IM_ASSERT(old_viewport->DpiScale == window->Viewport->DpiScale); // FIXME-DPI: Something went wrong
7380
0
                SetCurrentViewport(window, window->Viewport);
7381
0
                window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
7382
0
                SetCurrentWindow(window);
7383
0
            }
7384
7385
193k
        if (window->ViewportOwned)
7386
0
            WindowSyncOwnedViewport(window, parent_window_in_stack);
7387
7388
        // Calculate the range of allowed position for that window (to be movable and visible past safe area padding)
7389
        // When clamping to stay visible, we will enforce that window->Pos stays inside of visibility_rect.
7390
193k
        ImRect viewport_rect(window->Viewport->GetMainRect());
7391
193k
        ImRect viewport_work_rect(window->Viewport->GetWorkRect());
7392
193k
        ImVec2 visibility_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
7393
193k
        ImRect visibility_rect(viewport_work_rect.Min + visibility_padding, viewport_work_rect.Max - visibility_padding);
7394
7395
        // Clamp position/size so window stays visible within its viewport or monitor
7396
        // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
7397
        // FIXME: Similar to code in GetWindowAllowedExtentRect()
7398
193k
        if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow))
7399
169k
        {
7400
169k
            if (!window->ViewportOwned && viewport_rect.GetWidth() > 0 && viewport_rect.GetHeight() > 0.0f)
7401
169k
            {
7402
169k
                ClampWindowPos(window, visibility_rect);
7403
169k
            }
7404
0
            else if (window->ViewportOwned && g.PlatformIO.Monitors.Size > 0)
7405
0
            {
7406
0
                if (g.MovingWindow != NULL && window->RootWindowDockTree == g.MovingWindow->RootWindowDockTree)
7407
0
                {
7408
                    // While moving windows we allow them to straddle monitors (#7299, #3071)
7409
0
                    visibility_rect = g.PlatformMonitorsFullWorkRect;
7410
0
                }
7411
0
                else
7412
0
                {
7413
                    // When not moving ensure visible in its monitor
7414
                    // Lost windows (e.g. a monitor disconnected) will naturally moved to the fallback/dummy monitor aka the main viewport.
7415
0
                    const ImGuiPlatformMonitor* monitor = GetViewportPlatformMonitor(window->Viewport);
7416
0
                    visibility_rect = ImRect(monitor->WorkPos, monitor->WorkPos + monitor->WorkSize);
7417
0
                }
7418
0
                visibility_rect.Expand(-visibility_padding);
7419
0
                ClampWindowPos(window, visibility_rect);
7420
0
            }
7421
169k
        }
7422
193k
        window->Pos = ImTrunc(window->Pos);
7423
7424
        // Lock window rounding for the frame (so that altering them doesn't cause inconsistencies)
7425
        // Large values tend to lead to variety of artifacts and are not recommended.
7426
193k
        if (window->ViewportOwned || window->DockIsActive)
7427
0
            window->WindowRounding = 0.0f;
7428
193k
        else
7429
193k
            window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
7430
7431
        // For windows with title bar or menu bar, we clamp to FrameHeight(FontSize + FramePadding.y * 2.0f) to completely hide artifacts.
7432
        //if ((window->Flags & ImGuiWindowFlags_MenuBar) || !(window->Flags & ImGuiWindowFlags_NoTitleBar))
7433
        //    window->WindowRounding = ImMin(window->WindowRounding, g.FontSize + style.FramePadding.y * 2.0f);
7434
7435
        // Apply window focus (new and reactivated windows are moved to front)
7436
193k
        bool want_focus = false;
7437
193k
        if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
7438
3
        {
7439
3
            if (flags & ImGuiWindowFlags_Popup)
7440
0
                want_focus = true;
7441
3
            else if ((window->DockIsActive || (flags & ImGuiWindowFlags_ChildWindow) == 0) && !(flags & ImGuiWindowFlags_Tooltip))
7442
2
                want_focus = true;
7443
3
        }
7444
7445
        // [Test Engine] Register whole window in the item system (before submitting further decorations)
7446
#ifdef IMGUI_ENABLE_TEST_ENGINE
7447
        if (g.TestEngineHookItems)
7448
        {
7449
            IM_ASSERT(window->IDStack.Size == 1);
7450
            window->IDStack.Size = 0; // As window->IDStack[0] == window->ID here, make sure TestEngine doesn't erroneously see window as parent of itself.
7451
            IMGUI_TEST_ENGINE_ITEM_ADD(window->ID, window->Rect(), NULL);
7452
            IMGUI_TEST_ENGINE_ITEM_INFO(window->ID, window->Name, (g.HoveredWindow == window) ? ImGuiItemStatusFlags_HoveredRect : 0);
7453
            window->IDStack.Size = 1;
7454
        }
7455
#endif
7456
7457
        // Decide if we are going to handle borders and resize grips
7458
193k
        const bool handle_borders_and_resize_grips = (window->DockNodeAsHost || !window->DockIsActive);
7459
7460
        // Handle manual resize: Resize Grips, Borders, Gamepad
7461
193k
        int border_hovered = -1, border_held = -1;
7462
193k
        ImU32 resize_grip_col[4] = {};
7463
193k
        const int resize_grip_count = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup)) ? 0 : g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // Allow resize from lower-left if we have the mouse cursor feedback for it.
7464
193k
        const float resize_grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.10f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
7465
193k
        if (handle_borders_and_resize_grips && !window->Collapsed)
7466
132k
            if (int auto_fit_mask = UpdateWindowManualResize(window, size_auto_fit, &border_hovered, &border_held, resize_grip_count, &resize_grip_col[0], visibility_rect))
7467
0
            {
7468
0
                if (auto_fit_mask & (1 << ImGuiAxis_X))
7469
0
                    use_current_size_for_scrollbar_x = true;
7470
0
                if (auto_fit_mask & (1 << ImGuiAxis_Y))
7471
0
                    use_current_size_for_scrollbar_y = true;
7472
0
            }
7473
193k
        window->ResizeBorderHovered = (signed char)border_hovered;
7474
193k
        window->ResizeBorderHeld = (signed char)border_held;
7475
7476
        // Synchronize window --> viewport again and one last time (clamping and manual resize may have affected either)
7477
193k
        if (window->ViewportOwned)
7478
0
        {
7479
0
            if (!window->Viewport->PlatformRequestMove)
7480
0
                window->Viewport->Pos = window->Pos;
7481
0
            if (!window->Viewport->PlatformRequestResize)
7482
0
                window->Viewport->Size = window->Size;
7483
0
            window->Viewport->UpdateWorkRect();
7484
0
            viewport_rect = window->Viewport->GetMainRect();
7485
0
        }
7486
7487
        // Save last known viewport position within the window itself (so it can be saved in .ini file and restored)
7488
193k
        window->ViewportPos = window->Viewport->Pos;
7489
7490
        // SCROLLBAR VISIBILITY
7491
7492
        // Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size).
7493
193k
        if (!window->Collapsed)
7494
132k
        {
7495
            // When reading the current size we need to read it after size constraints have been applied.
7496
            // Intentionally use previous frame values for InnerRect and ScrollbarSizes.
7497
            // And when we use window->DecorationUp here it doesn't have ScrollbarSizes.y applied yet.
7498
132k
            ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2));
7499
132k
            ImVec2 avail_size_from_last_frame = window->InnerRect.GetSize() + scrollbar_sizes_from_last_frame;
7500
132k
            ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0, 0) : window->ContentSize + window->WindowPadding * 2.0f;
7501
132k
            float size_x_for_scrollbars = use_current_size_for_scrollbar_x ? avail_size_from_current_frame.x : avail_size_from_last_frame.x;
7502
132k
            float size_y_for_scrollbars = use_current_size_for_scrollbar_y ? avail_size_from_current_frame.y : avail_size_from_last_frame.y;
7503
            //bool scrollbar_y_from_last_frame = window->ScrollbarY; // FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons?
7504
132k
            window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));
7505
132k
            window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((needed_size_from_last_frame.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar));
7506
132k
            if (window->ScrollbarX && !window->ScrollbarY)
7507
4.54k
                window->ScrollbarY = (needed_size_from_last_frame.y > size_y_for_scrollbars - style.ScrollbarSize) && !(flags & ImGuiWindowFlags_NoScrollbar);
7508
132k
            window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
7509
7510
            // Amend the partially filled window->DecorationXXX values.
7511
132k
            window->DecoOuterSizeX2 += window->ScrollbarSizes.x;
7512
132k
            window->DecoOuterSizeY2 += window->ScrollbarSizes.y;
7513
132k
        }
7514
7515
        // UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING)
7516
        // Update various regions. Variables they depend on should be set above in this function.
7517
        // We set this up after processing the resize grip so that our rectangles doesn't lag by a frame.
7518
7519
        // Outer rectangle
7520
        // Not affected by window border size. Used by:
7521
        // - FindHoveredWindow() (w/ extra padding when border resize is enabled)
7522
        // - Begin() initial clipping rect for drawing window background and borders.
7523
        // - Begin() clipping whole child
7524
193k
        const ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect;
7525
193k
        const ImRect outer_rect = window->Rect();
7526
193k
        const ImRect title_bar_rect = window->TitleBarRect();
7527
193k
        window->OuterRectClipped = outer_rect;
7528
193k
        if (window->DockIsActive)
7529
0
            window->OuterRectClipped.Min.y += window->TitleBarHeight;
7530
193k
        window->OuterRectClipped.ClipWith(host_rect);
7531
7532
        // Inner rectangle
7533
        // Not affected by window border size. Used by:
7534
        // - InnerClipRect
7535
        // - ScrollToRectEx()
7536
        // - NavUpdatePageUpPageDown()
7537
        // - Scrollbar()
7538
193k
        window->InnerRect.Min.x = window->Pos.x + window->DecoOuterSizeX1;
7539
193k
        window->InnerRect.Min.y = window->Pos.y + window->DecoOuterSizeY1;
7540
193k
        window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->DecoOuterSizeX2;
7541
193k
        window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->DecoOuterSizeY2;
7542
7543
        // Inner clipping rectangle.
7544
        // - Extend a outside of normal work region up to borders.
7545
        // - This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space.
7546
        // - It also makes clipped items be more noticeable.
7547
        // - And is consistent on both axis (prior to 2024/05/03 ClipRect used WindowPadding.x * 0.5f on left and right edge), see #3312
7548
        // - Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
7549
        // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior.
7550
        // Affected by window/frame border size. Used by:
7551
        // - Begin() initial clip rect
7552
193k
        float top_border_size = (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize);
7553
193k
        window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + window->WindowBorderSize);
7554
193k
        window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y + top_border_size);
7555
193k
        window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerRect.Max.x - window->WindowBorderSize);
7556
193k
        window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y - window->WindowBorderSize);
7557
193k
        window->InnerClipRect.ClipWithFull(host_rect);
7558
7559
        // Default item width. Make it proportional to window size if window manually resizes
7560
193k
        if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
7561
193k
            window->ItemWidthDefault = ImTrunc(window->Size.x * 0.65f);
7562
0
        else
7563
0
            window->ItemWidthDefault = ImTrunc(g.FontSize * 16.0f);
7564
7565
        // SCROLLING
7566
7567
        // Lock down maximum scrolling
7568
        // The value of ScrollMax are ahead from ScrollbarX/ScrollbarY which is intentionally using InnerRect from previous rect in order to accommodate
7569
        // for right/bottom aligned items without creating a scrollbar.
7570
193k
        window->ScrollMax.x = ImMax(0.0f, window->ContentSize.x + window->WindowPadding.x * 2.0f - window->InnerRect.GetWidth());
7571
193k
        window->ScrollMax.y = ImMax(0.0f, window->ContentSize.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight());
7572
7573
        // Apply scrolling
7574
193k
        window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window);
7575
193k
        window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
7576
193k
        window->DecoInnerSizeX1 = window->DecoInnerSizeY1 = 0.0f;
7577
7578
        // DRAWING
7579
7580
        // Setup draw list and outer clipping rectangle
7581
193k
        IM_ASSERT(window->DrawList->CmdBuffer.Size == 1 && window->DrawList->CmdBuffer[0].ElemCount == 0);
7582
193k
        window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
7583
193k
        PushClipRect(host_rect.Min, host_rect.Max, false);
7584
7585
        // Child windows can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call (since 1.71)
7586
        // When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order.
7587
        // FIXME: User code may rely on explicit sorting of overlapping child window and would need to disable this somehow. Please get in contact if you are affected (github #4493)
7588
193k
        const bool is_undocked_or_docked_visible = !window->DockIsActive || window->DockTabIsVisible;
7589
193k
        if (is_undocked_or_docked_visible)
7590
193k
        {
7591
193k
            bool render_decorations_in_parent = false;
7592
193k
            if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
7593
23.7k
            {
7594
                // - We test overlap with the previous child window only (testing all would end up being O(log N) not a good investment here)
7595
                // - We disable this when the parent window has zero vertices, which is a common pattern leading to laying out multiple overlapping childs
7596
23.7k
                ImGuiWindow* previous_child = parent_window->DC.ChildWindows.Size >= 2 ? parent_window->DC.ChildWindows[parent_window->DC.ChildWindows.Size - 2] : NULL;
7597
23.7k
                bool previous_child_overlapping = previous_child ? previous_child->Rect().Overlaps(window->Rect()) : false;
7598
23.7k
                bool parent_is_empty = (parent_window->DrawList->VtxBuffer.Size == 0);
7599
23.7k
                if (window->DrawList->CmdBuffer.back().ElemCount == 0 && !parent_is_empty && !previous_child_overlapping)
7600
23.7k
                    render_decorations_in_parent = true;
7601
23.7k
            }
7602
193k
            if (render_decorations_in_parent)
7603
23.7k
                window->DrawList = parent_window->DrawList;
7604
7605
            // Handle title bar, scrollbar, resize grips and resize borders
7606
193k
            const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow;
7607
193k
            const bool title_bar_is_highlight = want_focus || (window_to_highlight && (window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight || (window->DockNode && window->DockNode == window_to_highlight->DockNode)));
7608
193k
            RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, handle_borders_and_resize_grips, resize_grip_count, resize_grip_col, resize_grip_draw_size);
7609
7610
193k
            if (render_decorations_in_parent)
7611
23.7k
                window->DrawList = &window->DrawListInst;
7612
193k
        }
7613
7614
        // UPDATE RECTANGLES (2- THOSE AFFECTED BY SCROLLING)
7615
7616
        // Work rectangle.
7617
        // Affected by window padding and border size. Used by:
7618
        // - Columns() for right-most edge
7619
        // - TreeNode(), CollapsingHeader() for right-most edge
7620
        // - BeginTabBar() for right-most edge
7621
193k
        const bool allow_scrollbar_x = !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar);
7622
193k
        const bool allow_scrollbar_y = !(flags & ImGuiWindowFlags_NoScrollbar);
7623
193k
        const float work_rect_size_x = (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : ImMax(allow_scrollbar_x ? window->ContentSize.x : 0.0f, window->Size.x - window->WindowPadding.x * 2.0f - (window->DecoOuterSizeX1 + window->DecoOuterSizeX2)));
7624
193k
        const float work_rect_size_y = (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : ImMax(allow_scrollbar_y ? window->ContentSize.y : 0.0f, window->Size.y - window->WindowPadding.y * 2.0f - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2)));
7625
193k
        window->WorkRect.Min.x = ImTrunc(window->InnerRect.Min.x - window->Scroll.x + ImMax(window->WindowPadding.x, window->WindowBorderSize));
7626
193k
        window->WorkRect.Min.y = ImTrunc(window->InnerRect.Min.y - window->Scroll.y + ImMax(window->WindowPadding.y, window->WindowBorderSize));
7627
193k
        window->WorkRect.Max.x = window->WorkRect.Min.x + work_rect_size_x;
7628
193k
        window->WorkRect.Max.y = window->WorkRect.Min.y + work_rect_size_y;
7629
193k
        window->ParentWorkRect = window->WorkRect;
7630
7631
        // [LEGACY] Content Region
7632
        // FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it.
7633
        // Unless explicit content size is specified by user, this currently represent the region leading to no scrolling.
7634
        // Used by:
7635
        // - Mouse wheel scrolling + many other things
7636
193k
        window->ContentRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x + window->DecoOuterSizeX1;
7637
193k
        window->ContentRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + window->DecoOuterSizeY1;
7638
193k
        window->ContentRegionRect.Max.x = window->ContentRegionRect.Min.x + (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : (window->Size.x - window->WindowPadding.x * 2.0f - (window->DecoOuterSizeX1 + window->DecoOuterSizeX2)));
7639
193k
        window->ContentRegionRect.Max.y = window->ContentRegionRect.Min.y + (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : (window->Size.y - window->WindowPadding.y * 2.0f - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2)));
7640
7641
        // Setup drawing context
7642
        // (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.)
7643
193k
        window->DC.Indent.x = window->DecoOuterSizeX1 + window->WindowPadding.x - window->Scroll.x;
7644
193k
        window->DC.GroupOffset.x = 0.0f;
7645
193k
        window->DC.ColumnsOffset.x = 0.0f;
7646
7647
        // Record the loss of precision of CursorStartPos which can happen due to really large scrolling amount.
7648
        // This is used by clipper to compensate and fix the most common use case of large scroll area. Easy and cheap, next best thing compared to switching everything to double or ImU64.
7649
193k
        double start_pos_highp_x = (double)window->Pos.x + window->WindowPadding.x - (double)window->Scroll.x + window->DecoOuterSizeX1 + window->DC.ColumnsOffset.x;
7650
193k
        double start_pos_highp_y = (double)window->Pos.y + window->WindowPadding.y - (double)window->Scroll.y + window->DecoOuterSizeY1;
7651
193k
        window->DC.CursorStartPos  = ImVec2((float)start_pos_highp_x, (float)start_pos_highp_y);
7652
193k
        window->DC.CursorStartPosLossyness = ImVec2((float)(start_pos_highp_x - window->DC.CursorStartPos.x), (float)(start_pos_highp_y - window->DC.CursorStartPos.y));
7653
193k
        window->DC.CursorPos = window->DC.CursorStartPos;
7654
193k
        window->DC.CursorPosPrevLine = window->DC.CursorPos;
7655
193k
        window->DC.CursorMaxPos = window->DC.CursorStartPos;
7656
193k
        window->DC.IdealMaxPos = window->DC.CursorStartPos;
7657
193k
        window->DC.CurrLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f);
7658
193k
        window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
7659
193k
        window->DC.IsSameLine = window->DC.IsSetPos = false;
7660
7661
193k
        window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
7662
193k
        window->DC.NavLayersActiveMask = window->DC.NavLayersActiveMaskNext;
7663
193k
        window->DC.NavLayersActiveMaskNext = 0x00;
7664
193k
        window->DC.NavIsScrollPushableX = true;
7665
193k
        window->DC.NavHideHighlightOneFrame = false;
7666
193k
        window->DC.NavWindowHasScrollY = (window->ScrollMax.y > 0.0f);
7667
7668
193k
        window->DC.MenuBarAppending = false;
7669
193k
        window->DC.MenuColumns.Update(style.ItemSpacing.x, window_just_activated_by_user);
7670
193k
        window->DC.TreeDepth = 0;
7671
193k
        window->DC.TreeHasStackDataDepthMask = 0x00;
7672
193k
        window->DC.ChildWindows.resize(0);
7673
193k
        window->DC.StateStorage = &window->StateStorage;
7674
193k
        window->DC.CurrentColumns = NULL;
7675
193k
        window->DC.LayoutType = ImGuiLayoutType_Vertical;
7676
193k
        window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical;
7677
7678
193k
        window->DC.ItemWidth = window->ItemWidthDefault;
7679
193k
        window->DC.TextWrapPos = -1.0f; // disabled
7680
193k
        window->DC.ItemWidthStack.resize(0);
7681
193k
        window->DC.TextWrapPosStack.resize(0);
7682
193k
        if (flags & ImGuiWindowFlags_Modal)
7683
0
            window->DC.ModalDimBgColor = ColorConvertFloat4ToU32(GetStyleColorVec4(ImGuiCol_ModalWindowDimBg));
7684
7685
193k
        if (window->AutoFitFramesX > 0)
7686
2
            window->AutoFitFramesX--;
7687
193k
        if (window->AutoFitFramesY > 0)
7688
2
            window->AutoFitFramesY--;
7689
7690
        // Clear SetNextWindowXXX data (can aim to move this higher in the function)
7691
193k
        g.NextWindowData.ClearFlags();
7692
7693
        // Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
7694
        // We ImGuiFocusRequestFlags_UnlessBelowModal to:
7695
        // - Avoid focusing a window that is created outside of a modal. This will prevent active modal from being closed.
7696
        // - Position window behind the modal that is not a begin-parent of this window.
7697
193k
        if (want_focus)
7698
2
            FocusWindow(window, ImGuiFocusRequestFlags_UnlessBelowModal);
7699
193k
        if (want_focus && window == g.NavWindow)
7700
2
            NavInitWindow(window, false); // <-- this is in the way for us to be able to defer and sort reappearing FocusWindow() calls
7701
7702
        // Close requested by platform window (apply to all windows in this viewport)
7703
193k
        if (p_open != NULL && window->Viewport->PlatformRequestClose && window->Viewport != GetMainViewport())
7704
0
        {
7705
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' closed by PlatformRequestClose\n", window->Name);
7706
0
            *p_open = false;
7707
0
            g.NavWindowingToggleLayer = false; // Assume user mapped PlatformRequestClose on ALT-F4 so we disable ALT for menu toggle. False positive not an issue. // FIXME-NAV: Try removing.
7708
0
        }
7709
7710
        // Title bar
7711
193k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
7712
169k
            RenderWindowTitleBarContents(window, ImRect(title_bar_rect.Min.x + window->WindowBorderSize, title_bar_rect.Min.y, title_bar_rect.Max.x - window->WindowBorderSize, title_bar_rect.Max.y), name, p_open);
7713
7714
        // Clear hit test shape every frame
7715
193k
        window->HitTestHoleSize.x = window->HitTestHoleSize.y = 0;
7716
7717
        // Pressing CTRL+C while holding on a window copy its content to the clipboard
7718
        // This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope.
7719
        // Maybe we can support CTRL+C on every element?
7720
        /*
7721
        //if (g.NavWindow == window && g.ActiveId == 0)
7722
        if (g.ActiveId == window->MoveId)
7723
            if (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_C))
7724
                LogToClipboard();
7725
        */
7726
7727
193k
        if (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)
7728
193k
        {
7729
            // Docking: Dragging a dockable window (or any of its child) turns it into a drag and drop source.
7730
            // We need to do this _before_ we overwrite window->DC.LastItemId below because BeginDockableDragDropSource() also overwrites it.
7731
193k
            if (g.MovingWindow == window && (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoDocking) == 0)
7732
0
                BeginDockableDragDropSource(window);
7733
7734
            // Docking: Any dockable window can act as a target. For dock node hosts we call BeginDockableDragDropTarget() in DockNodeUpdate() instead.
7735
193k
            if (g.DragDropActive && !(flags & ImGuiWindowFlags_NoDocking))
7736
0
                if (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != window)
7737
0
                    if ((window == window->RootWindowDockTree) && !(window->Flags & ImGuiWindowFlags_DockNodeHost))
7738
0
                        BeginDockableDragDropTarget(window);
7739
193k
        }
7740
7741
        // We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin().
7742
        // This is useful to allow creating context menus on title bar only, etc.
7743
193k
        SetLastItemDataForWindow(window, title_bar_rect);
7744
7745
        // [DEBUG]
7746
193k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
7747
193k
        if (g.DebugLocateId != 0 && (window->ID == g.DebugLocateId || window->MoveId == g.DebugLocateId))
7748
0
            DebugLocateItemResolveWithLastItem();
7749
193k
#endif
7750
7751
        // [Test Engine] Register title bar / tab with MoveId.
7752
#ifdef IMGUI_ENABLE_TEST_ENGINE
7753
        if (!(window->Flags & ImGuiWindowFlags_NoTitleBar))
7754
            IMGUI_TEST_ENGINE_ITEM_ADD(g.LastItemData.ID, g.LastItemData.Rect, &g.LastItemData);
7755
#endif
7756
193k
    }
7757
0
    else
7758
0
    {
7759
        // Skip refresh always mark active
7760
0
        if (window->SkipRefresh)
7761
0
            window->Active = true;
7762
7763
        // Append
7764
0
        SetCurrentViewport(window, window->Viewport);
7765
0
        SetCurrentWindow(window);
7766
0
        g.NextWindowData.ClearFlags();
7767
0
        SetLastItemDataForWindow(window, window->TitleBarRect());
7768
0
    }
7769
7770
193k
    if (!(flags & ImGuiWindowFlags_DockNodeHost) && !window->SkipRefresh)
7771
193k
        PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true);
7772
7773
    // Clear 'accessed' flag last thing (After PushClipRect which will set the flag. We want the flag to stay false when the default "Debug" window is unused)
7774
193k
    window->WriteAccessed = false;
7775
193k
    window->BeginCount++;
7776
7777
    // Update visibility
7778
193k
    if (first_begin_of_the_frame && !window->SkipRefresh)
7779
193k
    {
7780
        // When we are about to select this tab (which will only be visible on the _next frame_), flag it with a non-zero HiddenFramesCannotSkipItems.
7781
        // This will have the important effect of actually returning true in Begin() and not setting SkipItems, allowing an earlier submission of the window contents.
7782
        // This is analogous to regular windows being hidden from one frame.
7783
        // It is especially important as e.g. nested TabBars would otherwise generate flicker in the form of one empty frame, or focus requests won't be processed.
7784
193k
        if (window->DockIsActive && !window->DockTabIsVisible)
7785
0
        {
7786
0
            if (window->LastFrameJustFocused == g.FrameCount)
7787
0
                window->HiddenFramesCannotSkipItems = 1;
7788
0
            else
7789
0
                window->HiddenFramesCanSkipItems = 1;
7790
0
        }
7791
7792
193k
        if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_ChildMenu))
7793
23.7k
        {
7794
            // Child window can be out of sight and have "negative" clip windows.
7795
            // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar).
7796
23.7k
            IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0 || window->DockIsActive);
7797
23.7k
            const bool nav_request = (window->ChildFlags & ImGuiChildFlags_NavFlattened) && (g.NavAnyRequest && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
7798
23.7k
            if (!g.LogEnabled && !nav_request)
7799
23.7k
                if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y)
7800
0
                {
7801
0
                    if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
7802
0
                        window->HiddenFramesCannotSkipItems = 1;
7803
0
                    else
7804
0
                        window->HiddenFramesCanSkipItems = 1;
7805
0
                }
7806
7807
            // Hide along with parent or if parent is collapsed
7808
23.7k
            if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0))
7809
0
                window->HiddenFramesCanSkipItems = 1;
7810
23.7k
            if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCannotSkipItems > 0))
7811
1
                window->HiddenFramesCannotSkipItems = 1;
7812
23.7k
        }
7813
7814
        // Don't render if style alpha is 0.0 at the time of Begin(). This is arbitrary and inconsistent but has been there for a long while (may remove at some point)
7815
193k
        if (style.Alpha <= 0.0f)
7816
0
            window->HiddenFramesCanSkipItems = 1;
7817
7818
        // Update the Hidden flag
7819
193k
        bool hidden_regular = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0);
7820
193k
        window->Hidden = hidden_regular || (window->HiddenFramesForRenderOnly > 0);
7821
7822
        // Disable inputs for requested number of frames
7823
193k
        if (window->DisableInputsFrames > 0)
7824
0
        {
7825
0
            window->DisableInputsFrames--;
7826
0
            window->Flags |= ImGuiWindowFlags_NoInputs;
7827
0
        }
7828
7829
        // Update the SkipItems flag, used to early out of all items functions (no layout required)
7830
193k
        bool skip_items = false;
7831
193k
        if (window->Collapsed || !window->Active || hidden_regular)
7832
61.2k
            if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0)
7833
61.2k
                skip_items = true;
7834
193k
        window->SkipItems = skip_items;
7835
7836
        // Restore NavLayersActiveMaskNext to previous value when not visible, so a CTRL+Tab back can use a safe value.
7837
193k
        if (window->SkipItems)
7838
61.2k
            window->DC.NavLayersActiveMaskNext = window->DC.NavLayersActiveMask;
7839
7840
        // Sanity check: there are two spots which can set Appearing = true
7841
        // - when 'window_just_activated_by_user' is set -> HiddenFramesCannotSkipItems is set -> SkipItems always false
7842
        // - in BeginDocked() path when DockNodeIsVisible == DockTabIsVisible == true -> hidden _should_ be all zero // FIXME: Not formally proven, hence the assert.
7843
193k
        if (window->SkipItems && !window->Appearing)
7844
193k
            IM_ASSERT(window->Appearing == false); // Please report on GitHub if this triggers: https://github.com/ocornut/imgui/issues/4177
7845
193k
    }
7846
0
    else if (first_begin_of_the_frame)
7847
0
    {
7848
        // Skip refresh mode
7849
0
        window->SkipItems = true;
7850
0
    }
7851
7852
    // [DEBUG] io.ConfigDebugBeginReturnValue override return value to test Begin/End and BeginChild/EndChild behaviors.
7853
    // (The implicit fallback window is NOT automatically ended allowing it to always be able to receive commands without crashing)
7854
193k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
7855
193k
    if (!window->IsFallbackWindow)
7856
108k
        if ((g.IO.ConfigDebugBeginReturnValueOnce && window_just_created) || (g.IO.ConfigDebugBeginReturnValueLoop && g.DebugBeginReturnValueCullDepth == g.CurrentWindowStack.Size))
7857
0
        {
7858
0
            if (window->AutoFitFramesX > 0) { window->AutoFitFramesX++; }
7859
0
            if (window->AutoFitFramesY > 0) { window->AutoFitFramesY++; }
7860
0
            return false;
7861
0
        }
7862
193k
#endif
7863
7864
193k
    return !window->SkipItems;
7865
193k
}
7866
7867
static void ImGui::SetLastItemDataForWindow(ImGuiWindow* window, const ImRect& rect)
7868
193k
{
7869
193k
    ImGuiContext& g = *GImGui;
7870
193k
    if (window->DockIsActive)
7871
0
        SetLastItemData(window->MoveId, g.CurrentItemFlags, window->DockTabItemStatusFlags, window->DockTabItemRect);
7872
193k
    else
7873
193k
        SetLastItemData(window->MoveId, g.CurrentItemFlags, IsMouseHoveringRect(rect.Min, rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0, rect);
7874
193k
}
7875
7876
void ImGui::End()
7877
193k
{
7878
193k
    ImGuiContext& g = *GImGui;
7879
193k
    ImGuiWindow* window = g.CurrentWindow;
7880
7881
    // Error checking: verify that user hasn't called End() too many times!
7882
193k
    if (g.CurrentWindowStack.Size <= 1 && g.WithinFrameScopeWithImplicitWindow)
7883
0
    {
7884
0
        IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size > 1, "Calling End() too many times!");
7885
0
        return;
7886
0
    }
7887
193k
    ImGuiWindowStackData& window_stack_data = g.CurrentWindowStack.back();
7888
7889
    // Error checking: verify that user doesn't directly call End() on a child window.
7890
193k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_DockNodeHost) && !window->DockIsActive)
7891
193k
        IM_ASSERT_USER_ERROR(g.WithinEndChild, "Must call EndChild() and not End()!");
7892
7893
    // Close anything that is open
7894
193k
    if (window->DC.CurrentColumns)
7895
0
        EndColumns();
7896
193k
    if (!(window->Flags & ImGuiWindowFlags_DockNodeHost) && !window->SkipRefresh)   // Pop inner window clip rectangle
7897
193k
        PopClipRect();
7898
193k
    PopFocusScope();
7899
193k
    if (window_stack_data.DisabledOverrideReenable && window->RootWindow == window)
7900
0
        EndDisabledOverrideReenable();
7901
7902
193k
    if (window->SkipRefresh)
7903
0
    {
7904
0
        IM_ASSERT(window->DrawList == NULL);
7905
0
        window->DrawList = &window->DrawListInst;
7906
0
    }
7907
7908
    // Stop logging
7909
193k
    if (!(window->Flags & ImGuiWindowFlags_ChildWindow))    // FIXME: add more options for scope of logging
7910
169k
        LogFinish();
7911
7912
193k
    if (window->DC.IsSetPos)
7913
0
        ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
7914
7915
    // Docking: report contents sizes to parent to allow for auto-resize
7916
193k
    if (window->DockNode && window->DockTabIsVisible)
7917
0
        if (ImGuiWindow* host_window = window->DockNode->HostWindow)         // FIXME-DOCK
7918
0
            host_window->DC.CursorMaxPos = window->DC.CursorMaxPos + window->WindowPadding - host_window->WindowPadding;
7919
7920
    // Pop from window stack
7921
193k
    g.LastItemData = window_stack_data.ParentLastItemDataBackup;
7922
193k
    if (window->Flags & ImGuiWindowFlags_ChildMenu)
7923
0
        g.BeginMenuDepth--;
7924
193k
    if (window->Flags & ImGuiWindowFlags_Popup)
7925
0
        g.BeginPopupStack.pop_back();
7926
193k
    window_stack_data.StackSizesOnBegin.CompareWithContextState(&g);
7927
193k
    g.CurrentWindowStack.pop_back();
7928
193k
    SetCurrentWindow(g.CurrentWindowStack.Size == 0 ? NULL : g.CurrentWindowStack.back().Window);
7929
193k
    if (g.CurrentWindow)
7930
108k
        SetCurrentViewport(g.CurrentWindow, g.CurrentWindow->Viewport);
7931
193k
}
7932
7933
void ImGui::BringWindowToFocusFront(ImGuiWindow* window)
7934
9.53k
{
7935
9.53k
    ImGuiContext& g = *GImGui;
7936
9.53k
    IM_ASSERT(window == window->RootWindow);
7937
7938
9.53k
    const int cur_order = window->FocusOrder;
7939
9.53k
    IM_ASSERT(g.WindowsFocusOrder[cur_order] == window);
7940
9.53k
    if (g.WindowsFocusOrder.back() == window)
7941
9.53k
        return;
7942
7943
0
    const int new_order = g.WindowsFocusOrder.Size - 1;
7944
0
    for (int n = cur_order; n < new_order; n++)
7945
0
    {
7946
0
        g.WindowsFocusOrder[n] = g.WindowsFocusOrder[n + 1];
7947
0
        g.WindowsFocusOrder[n]->FocusOrder--;
7948
0
        IM_ASSERT(g.WindowsFocusOrder[n]->FocusOrder == n);
7949
0
    }
7950
0
    g.WindowsFocusOrder[new_order] = window;
7951
0
    window->FocusOrder = (short)new_order;
7952
0
}
7953
7954
void ImGui::BringWindowToDisplayFront(ImGuiWindow* window)
7955
9.53k
{
7956
9.53k
    ImGuiContext& g = *GImGui;
7957
9.53k
    ImGuiWindow* current_front_window = g.Windows.back();
7958
9.53k
    if (current_front_window == window || current_front_window->RootWindowDockTree == window) // Cheap early out (could be better)
7959
9.53k
        return;
7960
0
    for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window
7961
0
        if (g.Windows[i] == window)
7962
0
        {
7963
0
            memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*));
7964
0
            g.Windows[g.Windows.Size - 1] = window;
7965
0
            break;
7966
0
        }
7967
0
}
7968
7969
void ImGui::BringWindowToDisplayBack(ImGuiWindow* window)
7970
0
{
7971
0
    ImGuiContext& g = *GImGui;
7972
0
    if (g.Windows[0] == window)
7973
0
        return;
7974
0
    for (int i = 0; i < g.Windows.Size; i++)
7975
0
        if (g.Windows[i] == window)
7976
0
        {
7977
0
            memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*));
7978
0
            g.Windows[0] = window;
7979
0
            break;
7980
0
        }
7981
0
}
7982
7983
void ImGui::BringWindowToDisplayBehind(ImGuiWindow* window, ImGuiWindow* behind_window)
7984
0
{
7985
0
    IM_ASSERT(window != NULL && behind_window != NULL);
7986
0
    ImGuiContext& g = *GImGui;
7987
0
    window = window->RootWindow;
7988
0
    behind_window = behind_window->RootWindow;
7989
0
    int pos_wnd = FindWindowDisplayIndex(window);
7990
0
    int pos_beh = FindWindowDisplayIndex(behind_window);
7991
0
    if (pos_wnd < pos_beh)
7992
0
    {
7993
0
        size_t copy_bytes = (pos_beh - pos_wnd - 1) * sizeof(ImGuiWindow*);
7994
0
        memmove(&g.Windows.Data[pos_wnd], &g.Windows.Data[pos_wnd + 1], copy_bytes);
7995
0
        g.Windows[pos_beh - 1] = window;
7996
0
    }
7997
0
    else
7998
0
    {
7999
0
        size_t copy_bytes = (pos_wnd - pos_beh) * sizeof(ImGuiWindow*);
8000
0
        memmove(&g.Windows.Data[pos_beh + 1], &g.Windows.Data[pos_beh], copy_bytes);
8001
0
        g.Windows[pos_beh] = window;
8002
0
    }
8003
0
}
8004
8005
int ImGui::FindWindowDisplayIndex(ImGuiWindow* window)
8006
0
{
8007
0
    ImGuiContext& g = *GImGui;
8008
0
    return g.Windows.index_from_ptr(g.Windows.find(window));
8009
0
}
8010
8011
// Moving window to front of display and set focus (which happens to be back of our sorted list)
8012
void ImGui::FocusWindow(ImGuiWindow* window, ImGuiFocusRequestFlags flags)
8013
22.2k
{
8014
22.2k
    ImGuiContext& g = *GImGui;
8015
8016
    // Modal check?
8017
22.2k
    if ((flags & ImGuiFocusRequestFlags_UnlessBelowModal) && (g.NavWindow != window)) // Early out in common case.
8018
30
        if (ImGuiWindow* blocking_modal = FindBlockingModal(window))
8019
0
        {
8020
            // This block would typically be reached in two situations:
8021
            // - API call to FocusWindow() with a window under a modal and ImGuiFocusRequestFlags_UnlessBelowModal flag.
8022
            // - User clicking on void or anything behind a modal while a modal is open (window == NULL)
8023
0
            IMGUI_DEBUG_LOG_FOCUS("[focus] FocusWindow(\"%s\", UnlessBelowModal): prevented by \"%s\".\n", window ? window->Name : "<NULL>", blocking_modal->Name);
8024
0
            if (window && window == window->RootWindow && (window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
8025
0
                BringWindowToDisplayBehind(window, blocking_modal); // Still bring right under modal. (FIXME: Could move in focus list too?)
8026
0
            ClosePopupsOverWindow(GetTopMostPopupModal(), false); // Note how we need to use GetTopMostPopupModal() aad NOT blocking_modal, to handle nested modals
8027
0
            return;
8028
0
        }
8029
8030
    // Find last focused child (if any) and focus it instead.
8031
22.2k
    if ((flags & ImGuiFocusRequestFlags_RestoreFocusedChild) && window != NULL)
8032
0
        window = NavRestoreLastChildNavWindow(window);
8033
8034
    // Apply focus
8035
22.2k
    if (g.NavWindow != window)
8036
9.58k
    {
8037
9.58k
        SetNavWindow(window);
8038
9.58k
        if (window && g.NavDisableMouseHover)
8039
1.74k
            g.NavMousePosDirty = true;
8040
9.58k
        g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
8041
9.58k
        g.NavLayer = ImGuiNavLayer_Main;
8042
9.58k
        SetNavFocusScope(window ? window->NavRootFocusScopeId : 0);
8043
9.58k
        g.NavIdIsAlive = false;
8044
9.58k
        g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
8045
8046
        // Close popups if any
8047
9.58k
        ClosePopupsOverWindow(window, false);
8048
9.58k
    }
8049
8050
    // Move the root window to the top of the pile
8051
22.2k
    IM_ASSERT(window == NULL || window->RootWindowDockTree != NULL);
8052
22.2k
    ImGuiWindow* focus_front_window = window ? window->RootWindow : NULL;
8053
22.2k
    ImGuiWindow* display_front_window = window ? window->RootWindowDockTree : NULL;
8054
22.2k
    ImGuiDockNode* dock_node = window ? window->DockNode : NULL;
8055
22.2k
    bool active_id_window_is_dock_node_host = (g.ActiveIdWindow && dock_node && dock_node->HostWindow == g.ActiveIdWindow);
8056
8057
    // Steal active widgets. Some of the cases it triggers includes:
8058
    // - Focus a window while an InputText in another window is active, if focus happens before the old InputText can run.
8059
    // - When using Nav to activate menu items (due to timing of activating on press->new window appears->losing ActiveId)
8060
    // - Using dock host items (tab, collapse button) can trigger this before we redirect the ActiveIdWindow toward the child window.
8061
22.2k
    if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window)
8062
9
        if (!g.ActiveIdNoClearOnFocusLoss && !active_id_window_is_dock_node_host)
8063
9
            ClearActiveID();
8064
8065
    // Passing NULL allow to disable keyboard focus
8066
22.2k
    if (!window)
8067
12.7k
        return;
8068
9.53k
    window->LastFrameJustFocused = g.FrameCount;
8069
8070
    // Select in dock node
8071
    // For #2304 we avoid applying focus immediately before the tabbar is visible.
8072
    //if (dock_node && dock_node->TabBar)
8073
    //    dock_node->TabBar->SelectedTabId = dock_node->TabBar->NextSelectedTabId = window->TabId;
8074
8075
    // Bring to front
8076
9.53k
    BringWindowToFocusFront(focus_front_window);
8077
9.53k
    if (((window->Flags | focus_front_window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
8078
9.53k
        BringWindowToDisplayFront(display_front_window);
8079
9.53k
}
8080
8081
void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window, ImGuiViewport* filter_viewport, ImGuiFocusRequestFlags flags)
8082
0
{
8083
0
    ImGuiContext& g = *GImGui;
8084
0
    int start_idx = g.WindowsFocusOrder.Size - 1;
8085
0
    if (under_this_window != NULL)
8086
0
    {
8087
        // Aim at root window behind us, if we are in a child window that's our own root (see #4640)
8088
0
        int offset = -1;
8089
0
        while (under_this_window->Flags & ImGuiWindowFlags_ChildWindow)
8090
0
        {
8091
0
            under_this_window = under_this_window->ParentWindow;
8092
0
            offset = 0;
8093
0
        }
8094
0
        start_idx = FindWindowFocusIndex(under_this_window) + offset;
8095
0
    }
8096
0
    for (int i = start_idx; i >= 0; i--)
8097
0
    {
8098
        // We may later decide to test for different NoXXXInputs based on the active navigation input (mouse vs nav) but that may feel more confusing to the user.
8099
0
        ImGuiWindow* window = g.WindowsFocusOrder[i];
8100
0
        if (window == ignore_window || !window->WasActive)
8101
0
            continue;
8102
0
        if (filter_viewport != NULL && window->Viewport != filter_viewport)
8103
0
            continue;
8104
0
        if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs))
8105
0
        {
8106
            // FIXME-DOCK: When ImGuiFocusRequestFlags_RestoreFocusedChild is set...
8107
            // This is failing (lagging by one frame) for docked windows.
8108
            // If A and B are docked into window and B disappear, at the NewFrame() call site window->NavLastChildNavWindow will still point to B.
8109
            // We might leverage the tab order implicitly stored in window->DockNodeAsHost->TabBar (essentially the 'most_recently_selected_tab' code in tab bar will do that but on next update)
8110
            // to tell which is the "previous" window. Or we may leverage 'LastFrameFocused/LastFrameJustFocused' and have this function handle child window itself?
8111
0
            FocusWindow(window, flags);
8112
0
            return;
8113
0
        }
8114
0
    }
8115
0
    FocusWindow(NULL, flags);
8116
0
}
8117
8118
// Important: this alone doesn't alter current ImDrawList state. This is called by PushFont/PopFont only.
8119
void ImGui::SetCurrentFont(ImFont* font)
8120
84.9k
{
8121
84.9k
    ImGuiContext& g = *GImGui;
8122
84.9k
    IM_ASSERT(font && font->IsLoaded());    // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
8123
84.9k
    IM_ASSERT(font->Scale > 0.0f);
8124
84.9k
    g.Font = font;
8125
84.9k
    g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale);
8126
84.9k
    g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f;
8127
84.9k
    g.FontScale = g.FontSize / g.Font->FontSize;
8128
8129
84.9k
    ImFontAtlas* atlas = g.Font->ContainerAtlas;
8130
84.9k
    g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel;
8131
84.9k
    g.DrawListSharedData.TexUvLines = atlas->TexUvLines;
8132
84.9k
    g.DrawListSharedData.Font = g.Font;
8133
84.9k
    g.DrawListSharedData.FontSize = g.FontSize;
8134
84.9k
    g.DrawListSharedData.FontScale = g.FontScale;
8135
84.9k
}
8136
8137
void ImGui::PushFont(ImFont* font)
8138
0
{
8139
0
    ImGuiContext& g = *GImGui;
8140
0
    if (!font)
8141
0
        font = GetDefaultFont();
8142
0
    SetCurrentFont(font);
8143
0
    g.FontStack.push_back(font);
8144
0
    g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID);
8145
0
}
8146
8147
void  ImGui::PopFont()
8148
0
{
8149
0
    ImGuiContext& g = *GImGui;
8150
0
    g.CurrentWindow->DrawList->PopTextureID();
8151
0
    g.FontStack.pop_back();
8152
0
    SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back());
8153
0
}
8154
8155
void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled)
8156
23.7k
{
8157
23.7k
    ImGuiContext& g = *GImGui;
8158
23.7k
    ImGuiItemFlags item_flags = g.CurrentItemFlags;
8159
23.7k
    IM_ASSERT(item_flags == g.ItemFlagsStack.back());
8160
23.7k
    if (enabled)
8161
23.7k
        item_flags |= option;
8162
0
    else
8163
0
        item_flags &= ~option;
8164
23.7k
    g.CurrentItemFlags = item_flags;
8165
23.7k
    g.ItemFlagsStack.push_back(item_flags);
8166
23.7k
}
8167
8168
void ImGui::PopItemFlag()
8169
23.7k
{
8170
23.7k
    ImGuiContext& g = *GImGui;
8171
23.7k
    IM_ASSERT(g.ItemFlagsStack.Size > 1); // Too many calls to PopItemFlag() - we always leave a 0 at the bottom of the stack.
8172
23.7k
    g.ItemFlagsStack.pop_back();
8173
23.7k
    g.CurrentItemFlags = g.ItemFlagsStack.back();
8174
23.7k
}
8175
8176
// BeginDisabled()/EndDisabled()
8177
// - Those can be nested but it cannot be used to enable an already disabled section (a single BeginDisabled(true) in the stack is enough to keep everything disabled)
8178
// - Visually this is currently altering alpha, but it is expected that in a future styling system this would work differently.
8179
// - Feedback welcome at https://github.com/ocornut/imgui/issues/211
8180
// - BeginDisabled(false) essentially does nothing useful but is provided to facilitate use of boolean expressions. If you can avoid calling BeginDisabled(False)/EndDisabled() best to avoid it.
8181
// - Optimized shortcuts instead of PushStyleVar() + PushItemFlag()
8182
void ImGui::BeginDisabled(bool disabled)
8183
0
{
8184
0
    ImGuiContext& g = *GImGui;
8185
0
    bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
8186
0
    if (!was_disabled && disabled)
8187
0
    {
8188
0
        g.DisabledAlphaBackup = g.Style.Alpha;
8189
0
        g.Style.Alpha *= g.Style.DisabledAlpha; // PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * g.Style.DisabledAlpha);
8190
0
    }
8191
0
    if (was_disabled || disabled)
8192
0
        g.CurrentItemFlags |= ImGuiItemFlags_Disabled;
8193
0
    g.ItemFlagsStack.push_back(g.CurrentItemFlags); // FIXME-OPT: can we simply skip this and use DisabledStackSize?
8194
0
    g.DisabledStackSize++;
8195
0
}
8196
8197
void ImGui::EndDisabled()
8198
0
{
8199
0
    ImGuiContext& g = *GImGui;
8200
0
    IM_ASSERT(g.DisabledStackSize > 0);
8201
0
    g.DisabledStackSize--;
8202
0
    bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
8203
    //PopItemFlag();
8204
0
    g.ItemFlagsStack.pop_back();
8205
0
    g.CurrentItemFlags = g.ItemFlagsStack.back();
8206
0
    if (was_disabled && (g.CurrentItemFlags & ImGuiItemFlags_Disabled) == 0)
8207
0
        g.Style.Alpha = g.DisabledAlphaBackup; //PopStyleVar();
8208
0
}
8209
8210
// Could have been called BeginDisabledDisable() but it didn't want to be award nominated for most awkward function name.
8211
// Ideally we would use a shared e.g. BeginDisabled()->BeginDisabledEx() but earlier needs to be optimal.
8212
// The whole code for this is awkward, will reevaluate if we find a way to implement SetNextItemDisabled().
8213
void ImGui::BeginDisabledOverrideReenable()
8214
0
{
8215
0
    ImGuiContext& g = *GImGui;
8216
0
    IM_ASSERT(g.CurrentItemFlags & ImGuiItemFlags_Disabled);
8217
0
    g.Style.Alpha = g.DisabledAlphaBackup;
8218
0
    g.CurrentItemFlags &= ~ImGuiItemFlags_Disabled;
8219
0
    g.ItemFlagsStack.push_back(g.CurrentItemFlags);
8220
0
    g.DisabledStackSize++;
8221
0
}
8222
8223
void ImGui::EndDisabledOverrideReenable()
8224
0
{
8225
0
    ImGuiContext& g = *GImGui;
8226
0
    g.DisabledStackSize--;
8227
0
    IM_ASSERT(g.DisabledStackSize > 0);
8228
0
    g.ItemFlagsStack.pop_back();
8229
0
    g.CurrentItemFlags = g.ItemFlagsStack.back();
8230
0
    g.Style.Alpha = g.DisabledAlphaBackup * g.Style.DisabledAlpha;
8231
0
}
8232
8233
void ImGui::PushTextWrapPos(float wrap_pos_x)
8234
0
{
8235
0
    ImGuiWindow* window = GetCurrentWindow();
8236
0
    window->DC.TextWrapPosStack.push_back(window->DC.TextWrapPos);
8237
0
    window->DC.TextWrapPos = wrap_pos_x;
8238
0
}
8239
8240
void ImGui::PopTextWrapPos()
8241
0
{
8242
0
    ImGuiWindow* window = GetCurrentWindow();
8243
0
    window->DC.TextWrapPos = window->DC.TextWrapPosStack.back();
8244
0
    window->DC.TextWrapPosStack.pop_back();
8245
0
}
8246
8247
static ImGuiWindow* GetCombinedRootWindow(ImGuiWindow* window, bool popup_hierarchy, bool dock_hierarchy)
8248
0
{
8249
0
    ImGuiWindow* last_window = NULL;
8250
0
    while (last_window != window)
8251
0
    {
8252
0
        last_window = window;
8253
0
        window = window->RootWindow;
8254
0
        if (popup_hierarchy)
8255
0
            window = window->RootWindowPopupTree;
8256
0
    if (dock_hierarchy)
8257
0
      window = window->RootWindowDockTree;
8258
0
  }
8259
0
    return window;
8260
0
}
8261
8262
bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent, bool popup_hierarchy, bool dock_hierarchy)
8263
0
{
8264
0
    ImGuiWindow* window_root = GetCombinedRootWindow(window, popup_hierarchy, dock_hierarchy);
8265
0
    if (window_root == potential_parent)
8266
0
        return true;
8267
0
    while (window != NULL)
8268
0
    {
8269
0
        if (window == potential_parent)
8270
0
            return true;
8271
0
        if (window == window_root) // end of chain
8272
0
            return false;
8273
0
        window = window->ParentWindow;
8274
0
    }
8275
0
    return false;
8276
0
}
8277
8278
bool ImGui::IsWindowWithinBeginStackOf(ImGuiWindow* window, ImGuiWindow* potential_parent)
8279
0
{
8280
0
    if (window->RootWindow == potential_parent)
8281
0
        return true;
8282
0
    while (window != NULL)
8283
0
    {
8284
0
        if (window == potential_parent)
8285
0
            return true;
8286
0
        window = window->ParentWindowInBeginStack;
8287
0
    }
8288
0
    return false;
8289
0
}
8290
8291
bool ImGui::IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_below)
8292
0
{
8293
0
    ImGuiContext& g = *GImGui;
8294
8295
    // It would be saner to ensure that display layer is always reflected in the g.Windows[] order, which would likely requires altering all manipulations of that array
8296
0
    const int display_layer_delta = GetWindowDisplayLayer(potential_above) - GetWindowDisplayLayer(potential_below);
8297
0
    if (display_layer_delta != 0)
8298
0
        return display_layer_delta > 0;
8299
8300
0
    for (int i = g.Windows.Size - 1; i >= 0; i--)
8301
0
    {
8302
0
        ImGuiWindow* candidate_window = g.Windows[i];
8303
0
        if (candidate_window == potential_above)
8304
0
            return true;
8305
0
        if (candidate_window == potential_below)
8306
0
            return false;
8307
0
    }
8308
0
    return false;
8309
0
}
8310
8311
// Is current window hovered and hoverable (e.g. not blocked by a popup/modal)? See ImGuiHoveredFlags_ for options.
8312
// IMPORTANT: If you are trying to check whether your mouse should be dispatched to Dear ImGui or to your underlying app,
8313
// you should not use this function! Use the 'io.WantCaptureMouse' boolean for that!
8314
// Refer to FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" for details.
8315
bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
8316
34.9k
{
8317
34.9k
    IM_ASSERT((flags & ~ImGuiHoveredFlags_AllowedMaskForIsWindowHovered) == 0 && "Invalid flags for IsWindowHovered()!");
8318
8319
34.9k
    ImGuiContext& g = *GImGui;
8320
34.9k
    ImGuiWindow* ref_window = g.HoveredWindow;
8321
34.9k
    ImGuiWindow* cur_window = g.CurrentWindow;
8322
34.9k
    if (ref_window == NULL)
8323
34.5k
        return false;
8324
8325
400
    if ((flags & ImGuiHoveredFlags_AnyWindow) == 0)
8326
400
    {
8327
400
        IM_ASSERT(cur_window); // Not inside a Begin()/End()
8328
400
        const bool popup_hierarchy = (flags & ImGuiHoveredFlags_NoPopupHierarchy) == 0;
8329
400
        const bool dock_hierarchy = (flags & ImGuiHoveredFlags_DockHierarchy) != 0;
8330
400
        if (flags & ImGuiHoveredFlags_RootWindow)
8331
0
            cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy);
8332
8333
400
        bool result;
8334
400
        if (flags & ImGuiHoveredFlags_ChildWindows)
8335
0
            result = IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy);
8336
400
        else
8337
400
            result = (ref_window == cur_window);
8338
400
        if (!result)
8339
386
            return false;
8340
400
    }
8341
8342
14
    if (!IsWindowContentHoverable(ref_window, flags))
8343
0
        return false;
8344
14
    if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
8345
14
        if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != ref_window->MoveId)
8346
0
            return false;
8347
8348
    // When changing hovered window we requires a bit of stationary delay before activating hover timer.
8349
    // FIXME: We don't support delay other than stationary one for now, other delay would need a way
8350
    // to fulfill the possibility that multiple IsWindowHovered() with varying flag could return true
8351
    // for different windows of the hierarchy. Possibly need a Hash(Current+Flags) ==> (Timer) cache.
8352
    // We can implement this for _Stationary because the data is linked to HoveredWindow rather than CurrentWindow.
8353
14
    if (flags & ImGuiHoveredFlags_ForTooltip)
8354
0
        flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipMouse);
8355
14
    if ((flags & ImGuiHoveredFlags_Stationary) != 0 && g.HoverWindowUnlockedStationaryId != ref_window->ID)
8356
0
        return false;
8357
8358
14
    return true;
8359
14
}
8360
8361
bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
8362
47.0k
{
8363
47.0k
    ImGuiContext& g = *GImGui;
8364
47.0k
    ImGuiWindow* ref_window = g.NavWindow;
8365
47.0k
    ImGuiWindow* cur_window = g.CurrentWindow;
8366
8367
47.0k
    if (ref_window == NULL)
8368
20.2k
        return false;
8369
26.8k
    if (flags & ImGuiFocusedFlags_AnyWindow)
8370
0
        return true;
8371
8372
26.8k
    IM_ASSERT(cur_window); // Not inside a Begin()/End()
8373
26.8k
    const bool popup_hierarchy = (flags & ImGuiFocusedFlags_NoPopupHierarchy) == 0;
8374
26.8k
    const bool dock_hierarchy = (flags & ImGuiFocusedFlags_DockHierarchy) != 0;
8375
26.8k
    if (flags & ImGuiHoveredFlags_RootWindow)
8376
0
        cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy);
8377
8378
26.8k
    if (flags & ImGuiHoveredFlags_ChildWindows)
8379
0
        return IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy);
8380
26.8k
    else
8381
26.8k
        return (ref_window == cur_window);
8382
26.8k
}
8383
8384
ImGuiID ImGui::GetWindowDockID()
8385
0
{
8386
0
    ImGuiContext& g = *GImGui;
8387
0
    return g.CurrentWindow->DockId;
8388
0
}
8389
8390
bool ImGui::IsWindowDocked()
8391
0
{
8392
0
    ImGuiContext& g = *GImGui;
8393
0
    return g.CurrentWindow->DockIsActive;
8394
0
}
8395
8396
// Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext)
8397
// Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmatically.
8398
// If you want a window to never be focused, you may use the e.g. NoInputs flag.
8399
bool ImGui::IsWindowNavFocusable(ImGuiWindow* window)
8400
0
{
8401
0
    return window->WasActive && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus);
8402
0
}
8403
8404
float ImGui::GetWindowWidth()
8405
9.12k
{
8406
9.12k
    ImGuiWindow* window = GImGui->CurrentWindow;
8407
9.12k
    return window->Size.x;
8408
9.12k
}
8409
8410
float ImGui::GetWindowHeight()
8411
9.22k
{
8412
9.22k
    ImGuiWindow* window = GImGui->CurrentWindow;
8413
9.22k
    return window->Size.y;
8414
9.22k
}
8415
8416
ImVec2 ImGui::GetWindowPos()
8417
0
{
8418
0
    ImGuiContext& g = *GImGui;
8419
0
    ImGuiWindow* window = g.CurrentWindow;
8420
0
    return window->Pos;
8421
0
}
8422
8423
void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
8424
0
{
8425
    // Test condition (NB: bit 0 is always true) and clear flags for next time
8426
0
    if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
8427
0
        return;
8428
8429
0
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8430
0
    window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8431
0
    window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX);
8432
8433
    // Set
8434
0
    const ImVec2 old_pos = window->Pos;
8435
0
    window->Pos = ImTrunc(pos);
8436
0
    ImVec2 offset = window->Pos - old_pos;
8437
0
    if (offset.x == 0.0f && offset.y == 0.0f)
8438
0
        return;
8439
0
    MarkIniSettingsDirty(window);
8440
    // FIXME: share code with TranslateWindow(), need to confirm whether the 3 rect modified by TranslateWindow() are desirable here.
8441
0
    window->DC.CursorPos += offset;         // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor
8442
0
    window->DC.CursorMaxPos += offset;      // And more importantly we need to offset CursorMaxPos/CursorStartPos this so ContentSize calculation doesn't get affected.
8443
0
    window->DC.IdealMaxPos += offset;
8444
0
    window->DC.CursorStartPos += offset;
8445
0
}
8446
8447
void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond)
8448
0
{
8449
0
    ImGuiWindow* window = GetCurrentWindowRead();
8450
0
    SetWindowPos(window, pos, cond);
8451
0
}
8452
8453
void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond)
8454
0
{
8455
0
    if (ImGuiWindow* window = FindWindowByName(name))
8456
0
        SetWindowPos(window, pos, cond);
8457
0
}
8458
8459
ImVec2 ImGui::GetWindowSize()
8460
0
{
8461
0
    ImGuiWindow* window = GetCurrentWindowRead();
8462
0
    return window->Size;
8463
0
}
8464
8465
void ImGui::SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond)
8466
108k
{
8467
    // Test condition (NB: bit 0 is always true) and clear flags for next time
8468
108k
    if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
8469
84.9k
        return;
8470
8471
23.7k
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8472
23.7k
    window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8473
8474
    // Enable auto-fit (not done in BeginChild() path unless appearing or combined with ImGuiChildFlags_AlwaysAutoResize)
8475
23.7k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || window->Appearing || (window->ChildFlags & ImGuiChildFlags_AlwaysAutoResize) != 0)
8476
2
        window->AutoFitFramesX = (size.x <= 0.0f) ? 2 : 0;
8477
23.7k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || window->Appearing || (window->ChildFlags & ImGuiChildFlags_AlwaysAutoResize) != 0)
8478
2
        window->AutoFitFramesY = (size.y <= 0.0f) ? 2 : 0;
8479
8480
    // Set
8481
23.7k
    ImVec2 old_size = window->SizeFull;
8482
23.7k
    if (size.x <= 0.0f)
8483
0
        window->AutoFitOnlyGrows = false;
8484
23.7k
    else
8485
23.7k
        window->SizeFull.x = IM_TRUNC(size.x);
8486
23.7k
    if (size.y <= 0.0f)
8487
0
        window->AutoFitOnlyGrows = false;
8488
23.7k
    else
8489
23.7k
        window->SizeFull.y = IM_TRUNC(size.y);
8490
23.7k
    if (old_size.x != window->SizeFull.x || old_size.y != window->SizeFull.y)
8491
22.9k
        MarkIniSettingsDirty(window);
8492
23.7k
}
8493
8494
void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond)
8495
0
{
8496
0
    SetWindowSize(GImGui->CurrentWindow, size, cond);
8497
0
}
8498
8499
void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond)
8500
0
{
8501
0
    if (ImGuiWindow* window = FindWindowByName(name))
8502
0
        SetWindowSize(window, size, cond);
8503
0
}
8504
8505
void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond)
8506
0
{
8507
    // Test condition (NB: bit 0 is always true) and clear flags for next time
8508
0
    if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
8509
0
        return;
8510
0
    window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8511
8512
    // Set
8513
0
    window->Collapsed = collapsed;
8514
0
}
8515
8516
void ImGui::SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size)
8517
0
{
8518
0
    IM_ASSERT(window->HitTestHoleSize.x == 0);     // We don't support multiple holes/hit test filters
8519
0
    window->HitTestHoleSize = ImVec2ih(size);
8520
0
    window->HitTestHoleOffset = ImVec2ih(pos - window->Pos);
8521
0
}
8522
8523
void ImGui::SetWindowHiddenAndSkipItemsForCurrentFrame(ImGuiWindow* window)
8524
0
{
8525
0
    window->Hidden = window->SkipItems = true;
8526
0
    window->HiddenFramesCanSkipItems = 1;
8527
0
}
8528
8529
void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond)
8530
0
{
8531
0
    SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond);
8532
0
}
8533
8534
bool ImGui::IsWindowCollapsed()
8535
0
{
8536
0
    ImGuiWindow* window = GetCurrentWindowRead();
8537
0
    return window->Collapsed;
8538
0
}
8539
8540
bool ImGui::IsWindowAppearing()
8541
0
{
8542
0
    ImGuiWindow* window = GetCurrentWindowRead();
8543
0
    return window->Appearing;
8544
0
}
8545
8546
void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond)
8547
0
{
8548
0
    if (ImGuiWindow* window = FindWindowByName(name))
8549
0
        SetWindowCollapsed(window, collapsed, cond);
8550
0
}
8551
8552
void ImGui::SetWindowFocus()
8553
9.12k
{
8554
9.12k
    FocusWindow(GImGui->CurrentWindow);
8555
9.12k
}
8556
8557
void ImGui::SetWindowFocus(const char* name)
8558
0
{
8559
0
    if (name)
8560
0
    {
8561
0
        if (ImGuiWindow* window = FindWindowByName(name))
8562
0
            FocusWindow(window);
8563
0
    }
8564
0
    else
8565
0
    {
8566
0
        FocusWindow(NULL);
8567
0
    }
8568
0
}
8569
8570
void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot)
8571
0
{
8572
0
    ImGuiContext& g = *GImGui;
8573
0
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8574
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasPos;
8575
0
    g.NextWindowData.PosVal = pos;
8576
0
    g.NextWindowData.PosPivotVal = pivot;
8577
0
    g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;
8578
0
    g.NextWindowData.PosUndock = true;
8579
0
}
8580
8581
void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
8582
108k
{
8583
108k
    ImGuiContext& g = *GImGui;
8584
108k
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8585
108k
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSize;
8586
108k
    g.NextWindowData.SizeVal = size;
8587
108k
    g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always;
8588
108k
}
8589
8590
// For each axis:
8591
// - Use 0.0f as min or FLT_MAX as max if you don't want limits, e.g. size_min = (500.0f, 0.0f), size_max = (FLT_MAX, FLT_MAX) sets a minimum width.
8592
// - Use -1 for both min and max of same axis to preserve current size which itself is a constraint.
8593
// - See "Demo->Examples->Constrained-resizing window" for examples.
8594
void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data)
8595
0
{
8596
0
    ImGuiContext& g = *GImGui;
8597
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSizeConstraint;
8598
0
    g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);
8599
0
    g.NextWindowData.SizeCallback = custom_callback;
8600
0
    g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;
8601
0
}
8602
8603
// Content size = inner scrollable rectangle, padded with WindowPadding.
8604
// SetNextWindowContentSize(ImVec2(100,100) + ImGuiWindowFlags_AlwaysAutoResize will always allow submitting a 100x100 item.
8605
void ImGui::SetNextWindowContentSize(const ImVec2& size)
8606
0
{
8607
0
    ImGuiContext& g = *GImGui;
8608
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasContentSize;
8609
0
    g.NextWindowData.ContentSizeVal = ImTrunc(size);
8610
0
}
8611
8612
void ImGui::SetNextWindowScroll(const ImVec2& scroll)
8613
0
{
8614
0
    ImGuiContext& g = *GImGui;
8615
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasScroll;
8616
0
    g.NextWindowData.ScrollVal = scroll;
8617
0
}
8618
8619
void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
8620
0
{
8621
0
    ImGuiContext& g = *GImGui;
8622
0
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8623
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasCollapsed;
8624
0
    g.NextWindowData.CollapsedVal = collapsed;
8625
0
    g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;
8626
0
}
8627
8628
void ImGui::SetNextWindowFocus()
8629
0
{
8630
0
    ImGuiContext& g = *GImGui;
8631
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasFocus;
8632
0
}
8633
8634
void ImGui::SetNextWindowBgAlpha(float alpha)
8635
0
{
8636
0
    ImGuiContext& g = *GImGui;
8637
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasBgAlpha;
8638
0
    g.NextWindowData.BgAlphaVal = alpha;
8639
0
}
8640
8641
void ImGui::SetNextWindowViewport(ImGuiID id)
8642
0
{
8643
0
    ImGuiContext& g = *GImGui;
8644
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasViewport;
8645
0
    g.NextWindowData.ViewportId = id;
8646
0
}
8647
8648
void ImGui::SetNextWindowDockID(ImGuiID id, ImGuiCond cond)
8649
0
{
8650
0
    ImGuiContext& g = *GImGui;
8651
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasDock;
8652
0
    g.NextWindowData.DockCond = cond ? cond : ImGuiCond_Always;
8653
0
    g.NextWindowData.DockId = id;
8654
0
}
8655
8656
void ImGui::SetNextWindowClass(const ImGuiWindowClass* window_class)
8657
0
{
8658
0
    ImGuiContext& g = *GImGui;
8659
0
    IM_ASSERT((window_class->ViewportFlagsOverrideSet & window_class->ViewportFlagsOverrideClear) == 0); // Cannot set both set and clear for the same bit
8660
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasWindowClass;
8661
0
    g.NextWindowData.WindowClass = *window_class;
8662
0
}
8663
8664
// This is experimental and meant to be a toy for exploring a future/wider range of features.
8665
void ImGui::SetNextWindowRefreshPolicy(ImGuiWindowRefreshFlags flags)
8666
0
{
8667
0
    ImGuiContext& g = *GImGui;
8668
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasRefreshPolicy;
8669
0
    g.NextWindowData.RefreshFlagsVal = flags;
8670
0
}
8671
8672
ImDrawList* ImGui::GetWindowDrawList()
8673
23.7k
{
8674
23.7k
    ImGuiWindow* window = GetCurrentWindow();
8675
23.7k
    return window->DrawList;
8676
23.7k
}
8677
8678
float ImGui::GetWindowDpiScale()
8679
0
{
8680
0
    ImGuiContext& g = *GImGui;
8681
0
    return g.CurrentDpiScale;
8682
0
}
8683
8684
ImGuiViewport* ImGui::GetWindowViewport()
8685
0
{
8686
0
    ImGuiContext& g = *GImGui;
8687
0
    IM_ASSERT(g.CurrentViewport != NULL && g.CurrentViewport == g.CurrentWindow->Viewport);
8688
0
    return g.CurrentViewport;
8689
0
}
8690
8691
ImFont* ImGui::GetFont()
8692
1.60M
{
8693
1.60M
    return GImGui->Font;
8694
1.60M
}
8695
8696
float ImGui::GetFontSize()
8697
1.61M
{
8698
1.61M
    return GImGui->FontSize;
8699
1.61M
}
8700
8701
ImVec2 ImGui::GetFontTexUvWhitePixel()
8702
0
{
8703
0
    return GImGui->DrawListSharedData.TexUvWhitePixel;
8704
0
}
8705
8706
void ImGui::SetWindowFontScale(float scale)
8707
0
{
8708
0
    IM_ASSERT(scale > 0.0f);
8709
0
    ImGuiContext& g = *GImGui;
8710
0
    ImGuiWindow* window = GetCurrentWindow();
8711
0
    window->FontWindowScale = scale;
8712
0
    g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
8713
0
    g.FontScale = g.DrawListSharedData.FontScale = g.FontSize / g.Font->FontSize;
8714
0
}
8715
8716
void ImGui::PushFocusScope(ImGuiID id)
8717
193k
{
8718
193k
    ImGuiContext& g = *GImGui;
8719
193k
    ImGuiFocusScopeData data;
8720
193k
    data.ID = id;
8721
193k
    data.WindowID = g.CurrentWindow->ID;
8722
193k
    g.FocusScopeStack.push_back(data);
8723
193k
    g.CurrentFocusScopeId = id;
8724
193k
}
8725
8726
void ImGui::PopFocusScope()
8727
193k
{
8728
193k
    ImGuiContext& g = *GImGui;
8729
193k
    if (g.FocusScopeStack.Size == 0)
8730
0
    {
8731
0
        IM_ASSERT_USER_ERROR(g.FocusScopeStack.Size > 0, "Calling PopFocusScope() too many times!");
8732
0
        return;
8733
0
    }
8734
193k
    g.FocusScopeStack.pop_back();
8735
193k
    g.CurrentFocusScopeId = g.FocusScopeStack.Size ? g.FocusScopeStack.back().ID : 0;
8736
193k
}
8737
8738
void ImGui::SetNavFocusScope(ImGuiID focus_scope_id)
8739
12.1k
{
8740
12.1k
    ImGuiContext& g = *GImGui;
8741
12.1k
    g.NavFocusScopeId = focus_scope_id;
8742
12.1k
    g.NavFocusRoute.resize(0); // Invalidate
8743
12.1k
    if (focus_scope_id == 0)
8744
4.92k
        return;
8745
7.18k
    IM_ASSERT(g.NavWindow != NULL);
8746
8747
    // Store current path (in reverse order)
8748
7.18k
    if (focus_scope_id == g.CurrentFocusScopeId)
8749
6.66k
    {
8750
        // Top of focus stack contains local focus scopes inside current window
8751
13.3k
        for (int n = g.FocusScopeStack.Size - 1; n >= 0 && g.FocusScopeStack.Data[n].WindowID == g.CurrentWindow->ID; n--)
8752
6.66k
            g.NavFocusRoute.push_back(g.FocusScopeStack.Data[n]);
8753
6.66k
    }
8754
521
    else if (focus_scope_id == g.NavWindow->NavRootFocusScopeId)
8755
519
        g.NavFocusRoute.push_back({ focus_scope_id, g.NavWindow->ID });
8756
2
    else
8757
2
        return;
8758
8759
    // Then follow on manually set ParentWindowForFocusRoute field (#6798)
8760
11.8k
    for (ImGuiWindow* window = g.NavWindow->ParentWindowForFocusRoute; window != NULL; window = window->ParentWindowForFocusRoute)
8761
4.66k
        g.NavFocusRoute.push_back({ window->NavRootFocusScopeId, window->ID });
8762
7.18k
    IM_ASSERT(g.NavFocusRoute.Size < 100); // Maximum depth is technically 251 as per CalcRoutingScore(): 254 - 3
8763
7.18k
}
8764
8765
// Focus = move navigation cursor, set scrolling, set focus window.
8766
void ImGui::FocusItem()
8767
0
{
8768
0
    ImGuiContext& g = *GImGui;
8769
0
    ImGuiWindow* window = g.CurrentWindow;
8770
0
    IMGUI_DEBUG_LOG_FOCUS("FocusItem(0x%08x) in window \"%s\"\n", g.LastItemData.ID, window->Name);
8771
0
    if (g.DragDropActive || g.MovingWindow != NULL) // FIXME: Opt-in flags for this?
8772
0
    {
8773
0
        IMGUI_DEBUG_LOG_FOCUS("FocusItem() ignored while DragDropActive!\n");
8774
0
        return;
8775
0
    }
8776
8777
0
    ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_FocusApi | ImGuiNavMoveFlags_NoSetNavHighlight | ImGuiNavMoveFlags_NoSelect;
8778
0
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
8779
0
    SetNavWindow(window);
8780
0
    NavMoveRequestSubmit(ImGuiDir_None, ImGuiDir_Up, move_flags, scroll_flags);
8781
0
    NavMoveRequestResolveWithLastItem(&g.NavMoveResultLocal);
8782
0
}
8783
8784
void ImGui::ActivateItemByID(ImGuiID id)
8785
0
{
8786
0
    ImGuiContext& g = *GImGui;
8787
0
    g.NavNextActivateId = id;
8788
0
    g.NavNextActivateFlags = ImGuiActivateFlags_None;
8789
0
}
8790
8791
// Note: this will likely be called ActivateItem() once we rework our Focus/Activation system!
8792
// But ActivateItem() should function without altering scroll/focus?
8793
void ImGui::SetKeyboardFocusHere(int offset)
8794
0
{
8795
0
    ImGuiContext& g = *GImGui;
8796
0
    ImGuiWindow* window = g.CurrentWindow;
8797
0
    IM_ASSERT(offset >= -1);    // -1 is allowed but not below
8798
0
    IMGUI_DEBUG_LOG_FOCUS("SetKeyboardFocusHere(%d) in window \"%s\"\n", offset, window->Name);
8799
8800
    // It makes sense in the vast majority of cases to never interrupt a drag and drop.
8801
    // When we refactor this function into ActivateItem() we may want to make this an option.
8802
    // MovingWindow is protected from most user inputs using SetActiveIdUsingNavAndKeys(), but
8803
    // is also automatically dropped in the event g.ActiveId is stolen.
8804
0
    if (g.DragDropActive || g.MovingWindow != NULL)
8805
0
    {
8806
0
        IMGUI_DEBUG_LOG_FOCUS("SetKeyboardFocusHere() ignored while DragDropActive!\n");
8807
0
        return;
8808
0
    }
8809
8810
0
    SetNavWindow(window);
8811
8812
0
    ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_Activate | ImGuiNavMoveFlags_FocusApi | ImGuiNavMoveFlags_NoSetNavHighlight;
8813
0
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
8814
0
    NavMoveRequestSubmit(ImGuiDir_None, offset < 0 ? ImGuiDir_Up : ImGuiDir_Down, move_flags, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
8815
0
    if (offset == -1)
8816
0
    {
8817
0
        NavMoveRequestResolveWithLastItem(&g.NavMoveResultLocal);
8818
0
    }
8819
0
    else
8820
0
    {
8821
0
        g.NavTabbingDir = 1;
8822
0
        g.NavTabbingCounter = offset + 1;
8823
0
    }
8824
0
}
8825
8826
void ImGui::SetItemDefaultFocus()
8827
0
{
8828
0
    ImGuiContext& g = *GImGui;
8829
0
    ImGuiWindow* window = g.CurrentWindow;
8830
0
    if (!window->Appearing)
8831
0
        return;
8832
0
    if (g.NavWindow != window->RootWindowForNav || (!g.NavInitRequest && g.NavInitResult.ID == 0) || g.NavLayer != window->DC.NavLayerCurrent)
8833
0
        return;
8834
8835
0
    g.NavInitRequest = false;
8836
0
    NavApplyItemToResult(&g.NavInitResult);
8837
0
    NavUpdateAnyRequestFlag();
8838
8839
    // Scroll could be done in NavInitRequestApplyResult() via an opt-in flag (we however don't want regular init requests to scroll)
8840
0
    if (!window->ClipRect.Contains(g.LastItemData.Rect))
8841
0
        ScrollToRectEx(window, g.LastItemData.Rect, ImGuiScrollFlags_None);
8842
0
}
8843
8844
void ImGui::SetStateStorage(ImGuiStorage* tree)
8845
0
{
8846
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8847
0
    window->DC.StateStorage = tree ? tree : &window->StateStorage;
8848
0
}
8849
8850
ImGuiStorage* ImGui::GetStateStorage()
8851
0
{
8852
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8853
0
    return window->DC.StateStorage;
8854
0
}
8855
8856
bool ImGui::IsRectVisible(const ImVec2& size)
8857
0
{
8858
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8859
0
    return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
8860
0
}
8861
8862
bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
8863
0
{
8864
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8865
0
    return window->ClipRect.Overlaps(ImRect(rect_min, rect_max));
8866
0
}
8867
8868
//-----------------------------------------------------------------------------
8869
// [SECTION] ID STACK
8870
//-----------------------------------------------------------------------------
8871
8872
// This is one of the very rare legacy case where we use ImGuiWindow methods,
8873
// it should ideally be flattened at some point but it's been used a lots by widgets.
8874
IM_MSVC_RUNTIME_CHECKS_OFF
8875
ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
8876
261k
{
8877
261k
    ImGuiID seed = IDStack.back();
8878
261k
    ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
8879
261k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8880
261k
    ImGuiContext& g = *Ctx;
8881
261k
    if (g.DebugHookIdInfo == id)
8882
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
8883
261k
#endif
8884
261k
    return id;
8885
261k
}
8886
8887
ImGuiID ImGuiWindow::GetID(const void* ptr)
8888
0
{
8889
0
    ImGuiID seed = IDStack.back();
8890
0
    ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);
8891
0
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8892
0
    ImGuiContext& g = *Ctx;
8893
0
    if (g.DebugHookIdInfo == id)
8894
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_Pointer, ptr, NULL);
8895
0
#endif
8896
0
    return id;
8897
0
}
8898
8899
ImGuiID ImGuiWindow::GetID(int n)
8900
142k
{
8901
142k
    ImGuiID seed = IDStack.back();
8902
142k
    ImGuiID id = ImHashData(&n, sizeof(n), seed);
8903
142k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8904
142k
    ImGuiContext& g = *Ctx;
8905
142k
    if (g.DebugHookIdInfo == id)
8906
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
8907
142k
#endif
8908
142k
    return id;
8909
142k
}
8910
8911
// This is only used in rare/specific situations to manufacture an ID out of nowhere.
8912
ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs)
8913
0
{
8914
0
    ImGuiID seed = IDStack.back();
8915
0
    ImRect r_rel = ImGui::WindowRectAbsToRel(this, r_abs);
8916
0
    ImGuiID id = ImHashData(&r_rel, sizeof(r_rel), seed);
8917
0
    return id;
8918
0
}
8919
8920
void ImGui::PushID(const char* str_id)
8921
23.7k
{
8922
23.7k
    ImGuiContext& g = *GImGui;
8923
23.7k
    ImGuiWindow* window = g.CurrentWindow;
8924
23.7k
    ImGuiID id = window->GetID(str_id);
8925
23.7k
    window->IDStack.push_back(id);
8926
23.7k
}
8927
8928
void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
8929
0
{
8930
0
    ImGuiContext& g = *GImGui;
8931
0
    ImGuiWindow* window = g.CurrentWindow;
8932
0
    ImGuiID id = window->GetID(str_id_begin, str_id_end);
8933
0
    window->IDStack.push_back(id);
8934
0
}
8935
8936
void ImGui::PushID(const void* ptr_id)
8937
0
{
8938
0
    ImGuiContext& g = *GImGui;
8939
0
    ImGuiWindow* window = g.CurrentWindow;
8940
0
    ImGuiID id = window->GetID(ptr_id);
8941
0
    window->IDStack.push_back(id);
8942
0
}
8943
8944
void ImGui::PushID(int int_id)
8945
0
{
8946
0
    ImGuiContext& g = *GImGui;
8947
0
    ImGuiWindow* window = g.CurrentWindow;
8948
0
    ImGuiID id = window->GetID(int_id);
8949
0
    window->IDStack.push_back(id);
8950
0
}
8951
8952
// Push a given id value ignoring the ID stack as a seed.
8953
void ImGui::PushOverrideID(ImGuiID id)
8954
0
{
8955
0
    ImGuiContext& g = *GImGui;
8956
0
    ImGuiWindow* window = g.CurrentWindow;
8957
0
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8958
0
    if (g.DebugHookIdInfo == id)
8959
0
        DebugHookIdInfo(id, ImGuiDataType_ID, NULL, NULL);
8960
0
#endif
8961
0
    window->IDStack.push_back(id);
8962
0
}
8963
8964
// Helper to avoid a common series of PushOverrideID -> GetID() -> PopID() call
8965
// (note that when using this pattern, ID Stack Tool will tend to not display the intermediate stack level.
8966
//  for that to work we would need to do PushOverrideID() -> ItemAdd() -> PopID() which would alter widget code a little more)
8967
ImGuiID ImGui::GetIDWithSeed(const char* str, const char* str_end, ImGuiID seed)
8968
0
{
8969
0
    ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
8970
0
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8971
0
    ImGuiContext& g = *GImGui;
8972
0
    if (g.DebugHookIdInfo == id)
8973
0
        DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
8974
0
#endif
8975
0
    return id;
8976
0
}
8977
8978
ImGuiID ImGui::GetIDWithSeed(int n, ImGuiID seed)
8979
0
{
8980
0
    ImGuiID id = ImHashData(&n, sizeof(n), seed);
8981
0
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8982
0
    ImGuiContext& g = *GImGui;
8983
0
    if (g.DebugHookIdInfo == id)
8984
0
        DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
8985
0
#endif
8986
0
    return id;
8987
0
}
8988
8989
void ImGui::PopID()
8990
23.7k
{
8991
23.7k
    ImGuiWindow* window = GImGui->CurrentWindow;
8992
23.7k
    IM_ASSERT(window->IDStack.Size > 1); // Too many PopID(), or could be popping in a wrong/different window?
8993
23.7k
    window->IDStack.pop_back();
8994
23.7k
}
8995
8996
ImGuiID ImGui::GetID(const char* str_id)
8997
0
{
8998
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8999
0
    return window->GetID(str_id);
9000
0
}
9001
9002
ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
9003
0
{
9004
0
    ImGuiWindow* window = GImGui->CurrentWindow;
9005
0
    return window->GetID(str_id_begin, str_id_end);
9006
0
}
9007
9008
ImGuiID ImGui::GetID(const void* ptr_id)
9009
0
{
9010
0
    ImGuiWindow* window = GImGui->CurrentWindow;
9011
0
    return window->GetID(ptr_id);
9012
0
}
9013
9014
ImGuiID ImGui::GetID(int int_id)
9015
0
{
9016
0
    ImGuiWindow* window = GImGui->CurrentWindow;
9017
0
    return window->GetID(int_id);
9018
0
}
9019
IM_MSVC_RUNTIME_CHECKS_RESTORE
9020
9021
//-----------------------------------------------------------------------------
9022
// [SECTION] INPUTS
9023
//-----------------------------------------------------------------------------
9024
// - GetModForModKey() [Internal]
9025
// - FixupKeyChord() [Internal]
9026
// - GetKeyData() [Internal]
9027
// - GetKeyIndex() [Internal]
9028
// - GetKeyName()
9029
// - GetKeyChordName() [Internal]
9030
// - CalcTypematicRepeatAmount() [Internal]
9031
// - GetTypematicRepeatRate() [Internal]
9032
// - GetKeyPressedAmount() [Internal]
9033
// - GetKeyMagnitude2d() [Internal]
9034
//-----------------------------------------------------------------------------
9035
// - UpdateKeyRoutingTable() [Internal]
9036
// - GetRoutingIdFromOwnerId() [Internal]
9037
// - GetShortcutRoutingData() [Internal]
9038
// - CalcRoutingScore() [Internal]
9039
// - SetShortcutRouting() [Internal]
9040
// - TestShortcutRouting() [Internal]
9041
//-----------------------------------------------------------------------------
9042
// - IsKeyDown()
9043
// - IsKeyPressed()
9044
// - IsKeyReleased()
9045
//-----------------------------------------------------------------------------
9046
// - IsMouseDown()
9047
// - IsMouseClicked()
9048
// - IsMouseReleased()
9049
// - IsMouseDoubleClicked()
9050
// - GetMouseClickedCount()
9051
// - IsMouseHoveringRect() [Internal]
9052
// - IsMouseDragPastThreshold() [Internal]
9053
// - IsMouseDragging()
9054
// - GetMousePos()
9055
// - SetMousePos() [Internal]
9056
// - GetMousePosOnOpeningCurrentPopup()
9057
// - IsMousePosValid()
9058
// - IsAnyMouseDown()
9059
// - GetMouseDragDelta()
9060
// - ResetMouseDragDelta()
9061
// - GetMouseCursor()
9062
// - SetMouseCursor()
9063
//-----------------------------------------------------------------------------
9064
// - UpdateAliasKey()
9065
// - GetMergedModsFromKeys()
9066
// - UpdateKeyboardInputs()
9067
// - UpdateMouseInputs()
9068
//-----------------------------------------------------------------------------
9069
// - LockWheelingWindow [Internal]
9070
// - FindBestWheelingWindow [Internal]
9071
// - UpdateMouseWheel() [Internal]
9072
//-----------------------------------------------------------------------------
9073
// - SetNextFrameWantCaptureKeyboard()
9074
// - SetNextFrameWantCaptureMouse()
9075
//-----------------------------------------------------------------------------
9076
// - GetInputSourceName() [Internal]
9077
// - DebugPrintInputEvent() [Internal]
9078
// - UpdateInputEvents() [Internal]
9079
//-----------------------------------------------------------------------------
9080
// - GetKeyOwner() [Internal]
9081
// - TestKeyOwner() [Internal]
9082
// - SetKeyOwner() [Internal]
9083
// - SetItemKeyOwner() [Internal]
9084
// - Shortcut() [Internal]
9085
//-----------------------------------------------------------------------------
9086
9087
static ImGuiKeyChord GetModForModKey(ImGuiKey key)
9088
0
{
9089
0
    if (key == ImGuiKey_LeftCtrl || key == ImGuiKey_RightCtrl)
9090
0
        return ImGuiMod_Ctrl;
9091
0
    if (key == ImGuiKey_LeftShift || key == ImGuiKey_RightShift)
9092
0
        return ImGuiMod_Shift;
9093
0
    if (key == ImGuiKey_LeftAlt || key == ImGuiKey_RightAlt)
9094
0
        return ImGuiMod_Alt;
9095
0
    if (key == ImGuiKey_LeftSuper || key == ImGuiKey_RightSuper)
9096
0
        return ImGuiMod_Super;
9097
0
    return ImGuiMod_None;
9098
0
}
9099
9100
ImGuiKeyChord ImGui::FixupKeyChord(ImGuiKeyChord key_chord)
9101
339k
{
9102
    // Add ImGuiMod_XXXX when a corresponding ImGuiKey_LeftXXX/ImGuiKey_RightXXX is specified.
9103
339k
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9104
339k
    if (IsModKey(key))
9105
0
        key_chord |= GetModForModKey(key);
9106
339k
    return key_chord;
9107
339k
}
9108
9109
ImGuiKeyData* ImGui::GetKeyData(ImGuiContext* ctx, ImGuiKey key)
9110
2.43M
{
9111
2.43M
    ImGuiContext& g = *ctx;
9112
9113
    // Special storage location for mods
9114
2.43M
    if (key & ImGuiMod_Mask_)
9115
679k
        key = ConvertSingleModFlagToKey(key);
9116
9117
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9118
    IM_ASSERT(key >= ImGuiKey_LegacyNativeKey_BEGIN && key < ImGuiKey_NamedKey_END);
9119
    if (IsLegacyKey(key) && g.IO.KeyMap[key] != -1)
9120
        key = (ImGuiKey)g.IO.KeyMap[key];  // Remap native->imgui or imgui->native
9121
#else
9122
2.43M
    IM_ASSERT(IsNamedKey(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend & user code.");
9123
2.43M
#endif
9124
2.43M
    return &g.IO.KeysData[key - ImGuiKey_KeysData_OFFSET];
9125
2.43M
}
9126
9127
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9128
// Formally moved to obsolete section in 1.90.5 in spite of documented as obsolete since 1.87
9129
ImGuiKey ImGui::GetKeyIndex(ImGuiKey key)
9130
{
9131
    ImGuiContext& g = *GImGui;
9132
    IM_ASSERT(IsNamedKey(key));
9133
    const ImGuiKeyData* key_data = GetKeyData(key);
9134
    return (ImGuiKey)(key_data - g.IO.KeysData);
9135
}
9136
#endif
9137
9138
// Those names a provided for debugging purpose and are not meant to be saved persistently not compared.
9139
static const char* const GKeyNames[] =
9140
{
9141
    "Tab", "LeftArrow", "RightArrow", "UpArrow", "DownArrow", "PageUp", "PageDown",
9142
    "Home", "End", "Insert", "Delete", "Backspace", "Space", "Enter", "Escape",
9143
    "LeftCtrl", "LeftShift", "LeftAlt", "LeftSuper", "RightCtrl", "RightShift", "RightAlt", "RightSuper", "Menu",
9144
    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H",
9145
    "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
9146
    "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12",
9147
    "F13", "F14", "F15", "F16", "F17", "F18", "F19", "F20", "F21", "F22", "F23", "F24",
9148
    "Apostrophe", "Comma", "Minus", "Period", "Slash", "Semicolon", "Equal", "LeftBracket",
9149
    "Backslash", "RightBracket", "GraveAccent", "CapsLock", "ScrollLock", "NumLock", "PrintScreen",
9150
    "Pause", "Keypad0", "Keypad1", "Keypad2", "Keypad3", "Keypad4", "Keypad5", "Keypad6",
9151
    "Keypad7", "Keypad8", "Keypad9", "KeypadDecimal", "KeypadDivide", "KeypadMultiply",
9152
    "KeypadSubtract", "KeypadAdd", "KeypadEnter", "KeypadEqual",
9153
    "AppBack", "AppForward",
9154
    "GamepadStart", "GamepadBack",
9155
    "GamepadFaceLeft", "GamepadFaceRight", "GamepadFaceUp", "GamepadFaceDown",
9156
    "GamepadDpadLeft", "GamepadDpadRight", "GamepadDpadUp", "GamepadDpadDown",
9157
    "GamepadL1", "GamepadR1", "GamepadL2", "GamepadR2", "GamepadL3", "GamepadR3",
9158
    "GamepadLStickLeft", "GamepadLStickRight", "GamepadLStickUp", "GamepadLStickDown",
9159
    "GamepadRStickLeft", "GamepadRStickRight", "GamepadRStickUp", "GamepadRStickDown",
9160
    "MouseLeft", "MouseRight", "MouseMiddle", "MouseX1", "MouseX2", "MouseWheelX", "MouseWheelY",
9161
    "ModCtrl", "ModShift", "ModAlt", "ModSuper", // ReservedForModXXX are showing the ModXXX names.
9162
};
9163
IM_STATIC_ASSERT(ImGuiKey_NamedKey_COUNT == IM_ARRAYSIZE(GKeyNames));
9164
9165
const char* ImGui::GetKeyName(ImGuiKey key)
9166
0
{
9167
0
    if (key == ImGuiKey_None)
9168
0
        return "None";
9169
0
#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
9170
0
    IM_ASSERT(IsNamedKeyOrMod(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend and user code.");
9171
#else
9172
    ImGuiContext& g = *GImGui;
9173
    if (IsLegacyKey(key))
9174
    {
9175
        if (g.IO.KeyMap[key] == -1)
9176
            return "N/A";
9177
        IM_ASSERT(IsNamedKey((ImGuiKey)g.IO.KeyMap[key]));
9178
        key = (ImGuiKey)g.IO.KeyMap[key];
9179
    }
9180
#endif
9181
0
    if (key & ImGuiMod_Mask_)
9182
0
        key = ConvertSingleModFlagToKey(key);
9183
0
    if (!IsNamedKey(key))
9184
0
        return "Unknown";
9185
9186
0
    return GKeyNames[key - ImGuiKey_NamedKey_BEGIN];
9187
0
}
9188
9189
// Return untranslated names: on macOS, Cmd key will show as Ctrl, Ctrl key will show as super.
9190
// Lifetime of return value: valid until next call to same function.
9191
const char* ImGui::GetKeyChordName(ImGuiKeyChord key_chord)
9192
0
{
9193
0
    ImGuiContext& g = *GImGui;
9194
9195
0
    const ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9196
0
    if (IsModKey(key))
9197
0
        key_chord &= ~GetModForModKey(key); // Return "Ctrl+LeftShift" instead of "Ctrl+Shift+LeftShift"
9198
0
    ImFormatString(g.TempKeychordName, IM_ARRAYSIZE(g.TempKeychordName), "%s%s%s%s%s",
9199
0
        (key_chord & ImGuiMod_Ctrl) ? "Ctrl+" : "",
9200
0
        (key_chord & ImGuiMod_Shift) ? "Shift+" : "",
9201
0
        (key_chord & ImGuiMod_Alt) ? "Alt+" : "",
9202
0
        (key_chord & ImGuiMod_Super) ? "Super+" : "",
9203
0
        (key != ImGuiKey_None || key_chord == ImGuiKey_None) ? GetKeyName(key) : "");
9204
0
    size_t len;
9205
0
    if (key == ImGuiKey_None && key_chord != 0)
9206
0
        if ((len = strlen(g.TempKeychordName)) != 0) // Remove trailing '+'
9207
0
            g.TempKeychordName[len - 1] = 0;
9208
0
    return g.TempKeychordName;
9209
0
}
9210
9211
// t0 = previous time (e.g.: g.Time - g.IO.DeltaTime)
9212
// t1 = current time (e.g.: g.Time)
9213
// An event is triggered at:
9214
//  t = 0.0f     t = repeat_delay,    t = repeat_delay + repeat_rate*N
9215
int ImGui::CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate)
9216
1.18k
{
9217
1.18k
    if (t1 == 0.0f)
9218
0
        return 1;
9219
1.18k
    if (t0 >= t1)
9220
0
        return 0;
9221
1.18k
    if (repeat_rate <= 0.0f)
9222
0
        return (t0 < repeat_delay) && (t1 >= repeat_delay);
9223
1.18k
    const int count_t0 = (t0 < repeat_delay) ? -1 : (int)((t0 - repeat_delay) / repeat_rate);
9224
1.18k
    const int count_t1 = (t1 < repeat_delay) ? -1 : (int)((t1 - repeat_delay) / repeat_rate);
9225
1.18k
    const int count = count_t1 - count_t0;
9226
1.18k
    return count;
9227
1.18k
}
9228
9229
void ImGui::GetTypematicRepeatRate(ImGuiInputFlags flags, float* repeat_delay, float* repeat_rate)
9230
10.2k
{
9231
10.2k
    ImGuiContext& g = *GImGui;
9232
10.2k
    switch (flags & ImGuiInputFlags_RepeatRateMask_)
9233
10.2k
    {
9234
3.53k
    case ImGuiInputFlags_RepeatRateNavMove:             *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.80f; return;
9235
0
    case ImGuiInputFlags_RepeatRateNavTweak:            *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.30f; return;
9236
6.72k
    case ImGuiInputFlags_RepeatRateDefault: default:    *repeat_delay = g.IO.KeyRepeatDelay * 1.00f; *repeat_rate = g.IO.KeyRepeatRate * 1.00f; return;
9237
10.2k
    }
9238
10.2k
}
9239
9240
// Return value representing the number of presses in the last time period, for the given repeat rate
9241
// (most often returns 0 or 1. The result is generally only >1 when RepeatRate is smaller than DeltaTime, aka large DeltaTime or fast RepeatRate)
9242
int ImGui::GetKeyPressedAmount(ImGuiKey key, float repeat_delay, float repeat_rate)
9243
1.18k
{
9244
1.18k
    ImGuiContext& g = *GImGui;
9245
1.18k
    const ImGuiKeyData* key_data = GetKeyData(key);
9246
1.18k
    if (!key_data->Down) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
9247
0
        return 0;
9248
1.18k
    const float t = key_data->DownDuration;
9249
1.18k
    return CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, repeat_delay, repeat_rate);
9250
1.18k
}
9251
9252
// Return 2D vector representing the combination of four cardinal direction, with analog value support (for e.g. ImGuiKey_GamepadLStick* values).
9253
ImVec2 ImGui::GetKeyMagnitude2d(ImGuiKey key_left, ImGuiKey key_right, ImGuiKey key_up, ImGuiKey key_down)
9254
0
{
9255
0
    return ImVec2(
9256
0
        GetKeyData(key_right)->AnalogValue - GetKeyData(key_left)->AnalogValue,
9257
0
        GetKeyData(key_down)->AnalogValue - GetKeyData(key_up)->AnalogValue);
9258
0
}
9259
9260
// Rewrite routing data buffers to strip old entries + sort by key to make queries not touch scattered data.
9261
//   Entries   D,A,B,B,A,C,B     --> A,A,B,B,B,C,D
9262
//   Index     A:1 B:2 C:5 D:0   --> A:0 B:2 C:5 D:6
9263
// See 'Metrics->Key Owners & Shortcut Routing' to visualize the result of that operation.
9264
static void ImGui::UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt)
9265
84.9k
{
9266
84.9k
    ImGuiContext& g = *GImGui;
9267
84.9k
    rt->EntriesNext.resize(0);
9268
13.1M
    for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
9269
13.0M
    {
9270
13.0M
        const int new_routing_start_idx = rt->EntriesNext.Size;
9271
13.0M
        ImGuiKeyRoutingData* routing_entry;
9272
13.0M
        for (int old_routing_idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; old_routing_idx != -1; old_routing_idx = routing_entry->NextEntryIndex)
9273
0
        {
9274
0
            routing_entry = &rt->Entries[old_routing_idx];
9275
0
            routing_entry->RoutingCurrScore = routing_entry->RoutingNextScore;
9276
0
            routing_entry->RoutingCurr = routing_entry->RoutingNext; // Update entry
9277
0
            routing_entry->RoutingNext = ImGuiKeyOwner_NoOwner;
9278
0
            routing_entry->RoutingNextScore = 255;
9279
0
            if (routing_entry->RoutingCurr == ImGuiKeyOwner_NoOwner)
9280
0
                continue;
9281
0
            rt->EntriesNext.push_back(*routing_entry); // Write alive ones into new buffer
9282
9283
            // Apply routing to owner if there's no owner already (RoutingCurr == None at this point)
9284
            // This is the result of previous frame's SetShortcutRouting() call.
9285
0
            if (routing_entry->Mods == g.IO.KeyMods)
9286
0
            {
9287
0
                ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
9288
0
                if (owner_data->OwnerCurr == ImGuiKeyOwner_NoOwner)
9289
0
                {
9290
0
                    owner_data->OwnerCurr = routing_entry->RoutingCurr;
9291
                    //IMGUI_DEBUG_LOG("SetKeyOwner(%s, owner_id=0x%08X) via Routing\n", GetKeyName(key), routing_entry->RoutingCurr);
9292
0
                }
9293
0
            }
9294
0
        }
9295
9296
        // Rewrite linked-list
9297
13.0M
        rt->Index[key - ImGuiKey_NamedKey_BEGIN] = (ImGuiKeyRoutingIndex)(new_routing_start_idx < rt->EntriesNext.Size ? new_routing_start_idx : -1);
9298
13.0M
        for (int n = new_routing_start_idx; n < rt->EntriesNext.Size; n++)
9299
0
            rt->EntriesNext[n].NextEntryIndex = (ImGuiKeyRoutingIndex)((n + 1 < rt->EntriesNext.Size) ? n + 1 : -1);
9300
13.0M
    }
9301
84.9k
    rt->Entries.swap(rt->EntriesNext); // Swap new and old indexes
9302
84.9k
}
9303
9304
// owner_id may be None/Any, but routing_id needs to be always be set, so we default to GetCurrentFocusScope().
9305
static inline ImGuiID GetRoutingIdFromOwnerId(ImGuiID owner_id)
9306
0
{
9307
0
    ImGuiContext& g = *GImGui;
9308
0
    return (owner_id != ImGuiKeyOwner_NoOwner && owner_id != ImGuiKeyOwner_Any) ? owner_id : g.CurrentFocusScopeId;
9309
0
}
9310
9311
ImGuiKeyRoutingData* ImGui::GetShortcutRoutingData(ImGuiKeyChord key_chord)
9312
0
{
9313
    // Majority of shortcuts will be Key + any number of Mods
9314
    // We accept _Single_ mod with ImGuiKey_None.
9315
    //  - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl);                    // Legal
9316
    //  - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl | ImGuiMod_Shift);   // Legal
9317
    //  - Shortcut(ImGuiMod_Ctrl);                                 // Legal
9318
    //  - Shortcut(ImGuiMod_Ctrl | ImGuiMod_Shift);                // Not legal
9319
0
    ImGuiContext& g = *GImGui;
9320
0
    ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
9321
0
    ImGuiKeyRoutingData* routing_data;
9322
0
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9323
0
    ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
9324
0
    if (key == ImGuiKey_None)
9325
0
        key = ConvertSingleModFlagToKey(mods);
9326
0
    IM_ASSERT(IsNamedKey(key));
9327
9328
    // Get (in the majority of case, the linked list will have one element so this should be 2 reads.
9329
    // Subsequent elements will be contiguous in memory as list is sorted/rebuilt in NewFrame).
9330
0
    for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; idx = routing_data->NextEntryIndex)
9331
0
    {
9332
0
        routing_data = &rt->Entries[idx];
9333
0
        if (routing_data->Mods == mods)
9334
0
            return routing_data;
9335
0
    }
9336
9337
    // Add to linked-list
9338
0
    ImGuiKeyRoutingIndex routing_data_idx = (ImGuiKeyRoutingIndex)rt->Entries.Size;
9339
0
    rt->Entries.push_back(ImGuiKeyRoutingData());
9340
0
    routing_data = &rt->Entries[routing_data_idx];
9341
0
    routing_data->Mods = (ImU16)mods;
9342
0
    routing_data->NextEntryIndex = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; // Setup linked list
9343
0
    rt->Index[key - ImGuiKey_NamedKey_BEGIN] = routing_data_idx;
9344
0
    return routing_data;
9345
0
}
9346
9347
// Current score encoding (lower is highest priority):
9348
//  -   0: ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverActive
9349
//  -   1: ImGuiInputFlags_ActiveItem or ImGuiInputFlags_RouteFocused (if item active)
9350
//  -   2: ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused
9351
//  -  3+: ImGuiInputFlags_RouteFocused (if window in focus-stack)
9352
//  - 254: ImGuiInputFlags_RouteGlobal
9353
//  - 255: never route
9354
// 'flags' should include an explicit routing policy
9355
static int CalcRoutingScore(ImGuiID focus_scope_id, ImGuiID owner_id, ImGuiInputFlags flags)
9356
0
{
9357
0
    ImGuiContext& g = *GImGui;
9358
0
    if (flags & ImGuiInputFlags_RouteFocused)
9359
0
    {
9360
        // ActiveID gets top priority
9361
        // (we don't check g.ActiveIdUsingAllKeys here. Routing is applied but if input ownership is tested later it may discard it)
9362
0
        if (owner_id != 0 && g.ActiveId == owner_id)
9363
0
            return 1;
9364
9365
        // Score based on distance to focused window (lower is better)
9366
        // Assuming both windows are submitting a routing request,
9367
        // - When Window....... is focused -> Window scores 3 (best), Window/ChildB scores 255 (no match)
9368
        // - When Window/ChildB is focused -> Window scores 4,        Window/ChildB scores 3 (best)
9369
        // Assuming only WindowA is submitting a routing request,
9370
        // - When Window/ChildB is focused -> Window scores 4 (best), Window/ChildB doesn't have a score.
9371
        // This essentially follow the window->ParentWindowForFocusRoute chain.
9372
0
        if (focus_scope_id == 0)
9373
0
            return 255;
9374
0
        for (int index_in_focus_path = 0; index_in_focus_path < g.NavFocusRoute.Size; index_in_focus_path++)
9375
0
            if (g.NavFocusRoute.Data[index_in_focus_path].ID == focus_scope_id)
9376
0
                return 3 + index_in_focus_path;
9377
0
        return 255;
9378
0
    }
9379
0
    else if (flags & ImGuiInputFlags_RouteActive)
9380
0
    {
9381
0
        if (owner_id != 0 && g.ActiveId == owner_id)
9382
0
            return 1;
9383
0
        return 255;
9384
0
    }
9385
0
    else if (flags & ImGuiInputFlags_RouteGlobal)
9386
0
    {
9387
0
        if (flags & ImGuiInputFlags_RouteOverActive)
9388
0
            return 0;
9389
0
        if (flags & ImGuiInputFlags_RouteOverFocused)
9390
0
            return 2;
9391
0
        return 254;
9392
0
    }
9393
0
    IM_ASSERT(0);
9394
0
    return 0;
9395
0
}
9396
9397
// We need this to filter some Shortcut() routes when an item e.g. an InputText() is active
9398
// e.g. ImGuiKey_G won't be considered a shortcut when item is active, but ImGuiMod|ImGuiKey_G can be.
9399
static bool IsKeyChordPotentiallyCharInput(ImGuiKeyChord key_chord)
9400
0
{
9401
    // Mimic 'ignore_char_inputs' logic in InputText()
9402
0
    ImGuiContext& g = *GImGui;
9403
9404
    // When the right mods are pressed it cannot be a char input so we won't filter the shortcut out.
9405
0
    ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
9406
0
    const bool ignore_char_inputs = ((mods & ImGuiMod_Ctrl) && !(mods & ImGuiMod_Alt)) || (g.IO.ConfigMacOSXBehaviors && (mods & ImGuiMod_Ctrl));
9407
0
    if (ignore_char_inputs)
9408
0
        return false;
9409
9410
    // Return true for A-Z, 0-9 and other keys associated to char inputs. Other keys such as F1-F12 won't be filtered.
9411
0
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9412
0
    return g.KeysMayBeCharInput.TestBit(key);
9413
0
}
9414
9415
// Request a desired route for an input chord (key + mods).
9416
// Return true if the route is available this frame.
9417
// - Routes and key ownership are attributed at the beginning of next frame based on best score and mod state.
9418
//   (Conceptually this does a "Submit for next frame" + "Test for current frame".
9419
//   As such, it could be called TrySetXXX or SubmitXXX, or the Submit and Test operations should be separate.)
9420
bool ImGui::SetShortcutRouting(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id)
9421
169k
{
9422
169k
    ImGuiContext& g = *GImGui;
9423
169k
    if ((flags & ImGuiInputFlags_RouteTypeMask_) == 0)
9424
0
        flags |= ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused | ImGuiInputFlags_RouteOverActive; // IMPORTANT: This is the default for SetShortcutRouting() but NOT Shortcut()
9425
169k
    else
9426
169k
        IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiInputFlags_RouteTypeMask_)); // Check that only 1 routing flag is used
9427
169k
    IM_ASSERT(owner_id != ImGuiKeyOwner_Any && owner_id != ImGuiKeyOwner_NoOwner);
9428
169k
    if (flags & (ImGuiInputFlags_RouteOverFocused | ImGuiInputFlags_RouteOverActive | ImGuiInputFlags_RouteUnlessBgFocused))
9429
169k
        IM_ASSERT(flags & ImGuiInputFlags_RouteGlobal);
9430
9431
    // Add ImGuiMod_XXXX when a corresponding ImGuiKey_LeftXXX/ImGuiKey_RightXXX is specified.
9432
169k
    key_chord = FixupKeyChord(key_chord);
9433
9434
    // [DEBUG] Debug break requested by user
9435
169k
    if (g.DebugBreakInShortcutRouting == key_chord)
9436
0
        IM_DEBUG_BREAK();
9437
9438
169k
    if (flags & ImGuiInputFlags_RouteUnlessBgFocused)
9439
0
        if (g.NavWindow == NULL)
9440
0
            return false;
9441
9442
    // Note how ImGuiInputFlags_RouteAlways won't set routing and thus won't set owner. May want to rework this?
9443
169k
    if (flags & ImGuiInputFlags_RouteAlways)
9444
169k
    {
9445
169k
        IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> always, no register\n", GetKeyChordName(key_chord), flags, owner_id);
9446
169k
        return true;
9447
169k
    }
9448
9449
    // Specific culling when there's an active item.
9450
0
    if (g.ActiveId != 0 && g.ActiveId != owner_id)
9451
0
    {
9452
0
        if (flags & ImGuiInputFlags_RouteActive)
9453
0
            return false;
9454
9455
        // Cull shortcuts with no modifiers when it could generate a character.
9456
        // e.g. Shortcut(ImGuiKey_G) also generates 'g' character, should not trigger when InputText() is active.
9457
        // but  Shortcut(Ctrl+G) should generally trigger when InputText() is active.
9458
        // TL;DR: lettered shortcut with no mods or with only Alt mod will not trigger while an item reading text input is active.
9459
        // (We cannot filter based on io.InputQueueCharacters[] contents because of trickling and key<>chars submission order are undefined)
9460
0
        if (g.IO.WantTextInput && IsKeyChordPotentiallyCharInput(key_chord))
9461
0
        {
9462
0
            IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> filtered as potential char input\n", GetKeyChordName(key_chord), flags, owner_id);
9463
0
            return false;
9464
0
        }
9465
9466
        // ActiveIdUsingAllKeyboardKeys trumps all for ActiveId
9467
0
        if ((flags & ImGuiInputFlags_RouteOverActive) == 0 && g.ActiveIdUsingAllKeyboardKeys)
9468
0
        {
9469
0
            ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9470
0
            if (key == ImGuiKey_None)
9471
0
                key = ConvertSingleModFlagToKey((ImGuiKey)(key_chord & ImGuiMod_Mask_));
9472
0
            if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
9473
0
                return false;
9474
0
        }
9475
0
    }
9476
9477
    // Where do we evaluate route for?
9478
0
    ImGuiID focus_scope_id = g.CurrentFocusScopeId;
9479
0
    if (flags & ImGuiInputFlags_RouteFromRootWindow)
9480
0
        focus_scope_id = g.CurrentWindow->RootWindow->ID; // See PushFocusScope() call in Begin()
9481
9482
0
    const int score = CalcRoutingScore(focus_scope_id, owner_id, flags);
9483
0
    IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> score %d\n", GetKeyChordName(key_chord), flags, owner_id, score);
9484
0
    if (score == 255)
9485
0
        return false;
9486
9487
    // Submit routing for NEXT frame (assuming score is sufficient)
9488
    // FIXME: Could expose a way to use a "serve last" policy for same score resolution (using <= instead of <).
9489
0
    ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord);
9490
    //const bool set_route = (flags & ImGuiInputFlags_ServeLast) ? (score <= routing_data->RoutingNextScore) : (score < routing_data->RoutingNextScore);
9491
0
    if (score < routing_data->RoutingNextScore)
9492
0
    {
9493
0
        routing_data->RoutingNext = owner_id;
9494
0
        routing_data->RoutingNextScore = (ImU8)score;
9495
0
    }
9496
9497
    // Return routing state for CURRENT frame
9498
0
    if (routing_data->RoutingCurr == owner_id)
9499
0
        IMGUI_DEBUG_LOG_INPUTROUTING("--> granting current route\n");
9500
0
    return routing_data->RoutingCurr == owner_id;
9501
0
}
9502
9503
// Currently unused by core (but used by tests)
9504
// Note: this cannot be turned into GetShortcutRouting() because we do the owner_id->routing_id translation, name would be more misleading.
9505
bool ImGui::TestShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id)
9506
0
{
9507
0
    const ImGuiID routing_id = GetRoutingIdFromOwnerId(owner_id);
9508
0
    key_chord = FixupKeyChord(key_chord);
9509
0
    ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord); // FIXME: Could avoid creating entry.
9510
0
    return routing_data->RoutingCurr == routing_id;
9511
0
}
9512
9513
// Note that Dear ImGui doesn't know the meaning/semantic of ImGuiKey from 0..511: they are legacy native keycodes.
9514
// Consider transitioning from 'IsKeyDown(MY_ENGINE_KEY_A)' (<1.87) to IsKeyDown(ImGuiKey_A) (>= 1.87)
9515
bool ImGui::IsKeyDown(ImGuiKey key)
9516
1.27M
{
9517
1.27M
    return IsKeyDown(key, ImGuiKeyOwner_Any);
9518
1.27M
}
9519
9520
bool ImGui::IsKeyDown(ImGuiKey key, ImGuiID owner_id)
9521
1.31M
{
9522
1.31M
    const ImGuiKeyData* key_data = GetKeyData(key);
9523
1.31M
    if (!key_data->Down)
9524
1.27M
        return false;
9525
35.7k
    if (!TestKeyOwner(key, owner_id))
9526
0
        return false;
9527
35.7k
    return true;
9528
35.7k
}
9529
9530
bool ImGui::IsKeyPressed(ImGuiKey key, bool repeat)
9531
153k
{
9532
153k
    return IsKeyPressed(key, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None, ImGuiKeyOwner_Any);
9533
153k
}
9534
9535
// Important: unless legacy IsKeyPressed(ImGuiKey, bool repeat=true) which DEFAULT to repeat, this requires EXPLICIT repeat.
9536
bool ImGui::IsKeyPressed(ImGuiKey key, ImGuiInputFlags flags, ImGuiID owner_id)
9537
502k
{
9538
502k
    const ImGuiKeyData* key_data = GetKeyData(key);
9539
502k
    if (!key_data->Down) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
9540
477k
        return false;
9541
25.6k
    const float t = key_data->DownDuration;
9542
25.6k
    if (t < 0.0f)
9543
0
        return false;
9544
25.6k
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsKeyPressed) == 0); // Passing flags not supported by this function!
9545
25.6k
    if (flags & (ImGuiInputFlags_RepeatRateMask_ | ImGuiInputFlags_RepeatUntilMask_)) // Setting any _RepeatXXX option enables _Repeat
9546
3.75k
        flags |= ImGuiInputFlags_Repeat;
9547
9548
25.6k
    bool pressed = (t == 0.0f);
9549
25.6k
    if (!pressed && (flags & ImGuiInputFlags_Repeat) != 0)
9550
10.2k
    {
9551
10.2k
        float repeat_delay, repeat_rate;
9552
10.2k
        GetTypematicRepeatRate(flags, &repeat_delay, &repeat_rate);
9553
10.2k
        pressed = (t > repeat_delay) && GetKeyPressedAmount(key, repeat_delay, repeat_rate) > 0;
9554
10.2k
        if (pressed && (flags & ImGuiInputFlags_RepeatUntilMask_))
9555
0
        {
9556
            // Slightly bias 'key_pressed_time' as DownDuration is an accumulation of DeltaTime which we compare to an absolute time value.
9557
            // Ideally we'd replace DownDuration with KeyPressedTime but it would break user's code.
9558
0
            ImGuiContext& g = *GImGui;
9559
0
            double key_pressed_time = g.Time - t + 0.00001f;
9560
0
            if ((flags & ImGuiInputFlags_RepeatUntilKeyModsChange) && (g.LastKeyModsChangeTime > key_pressed_time))
9561
0
                pressed = false;
9562
0
            if ((flags & ImGuiInputFlags_RepeatUntilKeyModsChangeFromNone) && (g.LastKeyModsChangeFromNoneTime > key_pressed_time))
9563
0
                pressed = false;
9564
0
            if ((flags & ImGuiInputFlags_RepeatUntilOtherKeyPress) && (g.LastKeyboardKeyPressTime > key_pressed_time))
9565
0
                pressed = false;
9566
0
        }
9567
10.2k
    }
9568
25.6k
    if (!pressed)
9569
21.8k
        return false;
9570
3.70k
    if (!TestKeyOwner(key, owner_id))
9571
0
        return false;
9572
3.70k
    return true;
9573
3.70k
}
9574
9575
bool ImGui::IsKeyReleased(ImGuiKey key)
9576
3.80k
{
9577
3.80k
    return IsKeyReleased(key, ImGuiKeyOwner_Any);
9578
3.80k
}
9579
9580
bool ImGui::IsKeyReleased(ImGuiKey key, ImGuiID owner_id)
9581
3.80k
{
9582
3.80k
    const ImGuiKeyData* key_data = GetKeyData(key);
9583
3.80k
    if (key_data->DownDurationPrev < 0.0f || key_data->Down)
9584
3.35k
        return false;
9585
446
    if (!TestKeyOwner(key, owner_id))
9586
0
        return false;
9587
446
    return true;
9588
446
}
9589
9590
bool ImGui::IsMouseDown(ImGuiMouseButton button)
9591
3
{
9592
3
    ImGuiContext& g = *GImGui;
9593
3
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9594
3
    return g.IO.MouseDown[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // should be same as IsKeyDown(MouseButtonToKey(button), ImGuiKeyOwner_Any), but this allows legacy code hijacking the io.Mousedown[] array.
9595
3
}
9596
9597
bool ImGui::IsMouseDown(ImGuiMouseButton button, ImGuiID owner_id)
9598
1
{
9599
1
    ImGuiContext& g = *GImGui;
9600
1
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9601
1
    return g.IO.MouseDown[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyDown(MouseButtonToKey(button), owner_id), but this allows legacy code hijacking the io.Mousedown[] array.
9602
1
}
9603
9604
bool ImGui::IsMouseClicked(ImGuiMouseButton button, bool repeat)
9605
10
{
9606
10
    return IsMouseClicked(button, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None, ImGuiKeyOwner_Any);
9607
10
}
9608
9609
bool ImGui::IsMouseClicked(ImGuiMouseButton button, ImGuiInputFlags flags, ImGuiID owner_id)
9610
155
{
9611
155
    ImGuiContext& g = *GImGui;
9612
155
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9613
155
    if (!g.IO.MouseDown[button]) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
9614
20
        return false;
9615
135
    const float t = g.IO.MouseDownDuration[button];
9616
135
    if (t < 0.0f)
9617
0
        return false;
9618
135
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsMouseClicked) == 0); // Passing flags not supported by this function! // FIXME: Could support RepeatRate and RepeatUntil flags here.
9619
9620
135
    const bool repeat = (flags & ImGuiInputFlags_Repeat) != 0;
9621
135
    const bool pressed = (t == 0.0f) || (repeat && t > g.IO.KeyRepeatDelay && CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0);
9622
135
    if (!pressed)
9623
134
        return false;
9624
9625
1
    if (!TestKeyOwner(MouseButtonToKey(button), owner_id))
9626
0
        return false;
9627
9628
1
    return true;
9629
1
}
9630
9631
bool ImGui::IsMouseReleased(ImGuiMouseButton button)
9632
0
{
9633
0
    ImGuiContext& g = *GImGui;
9634
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9635
0
    return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // Should be same as IsKeyReleased(MouseButtonToKey(button), ImGuiKeyOwner_Any)
9636
0
}
9637
9638
bool ImGui::IsMouseReleased(ImGuiMouseButton button, ImGuiID owner_id)
9639
145
{
9640
145
    ImGuiContext& g = *GImGui;
9641
145
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9642
145
    return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyReleased(MouseButtonToKey(button), owner_id)
9643
145
}
9644
9645
bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button)
9646
10
{
9647
10
    ImGuiContext& g = *GImGui;
9648
10
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9649
10
    return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any);
9650
10
}
9651
9652
bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button, ImGuiID owner_id)
9653
0
{
9654
0
    ImGuiContext& g = *GImGui;
9655
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9656
0
    return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(MouseButtonToKey(button), owner_id);
9657
0
}
9658
9659
int ImGui::GetMouseClickedCount(ImGuiMouseButton button)
9660
0
{
9661
0
    ImGuiContext& g = *GImGui;
9662
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9663
0
    return g.IO.MouseClickedCount[button];
9664
0
}
9665
9666
// Test if mouse cursor is hovering given rectangle
9667
// NB- Rectangle is clipped by our current clip setting
9668
// NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding)
9669
bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip)
9670
450k
{
9671
450k
    ImGuiContext& g = *GImGui;
9672
9673
    // Clip
9674
450k
    ImRect rect_clipped(r_min, r_max);
9675
450k
    if (clip)
9676
256k
        rect_clipped.ClipWith(g.CurrentWindow->ClipRect);
9677
9678
    // Hit testing, expanded for touch input
9679
450k
    if (!rect_clipped.ContainsWithPad(g.IO.MousePos, g.Style.TouchExtraPadding))
9680
442k
        return false;
9681
8.42k
    if (!g.MouseViewport->GetMainRect().Overlaps(rect_clipped))
9682
0
        return false;
9683
8.42k
    return true;
9684
8.42k
}
9685
9686
// Return if a mouse click/drag went past the given threshold. Valid to call during the MouseReleased frame.
9687
// [Internal] This doesn't test if the button is pressed
9688
bool ImGui::IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold)
9689
5
{
9690
5
    ImGuiContext& g = *GImGui;
9691
5
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9692
5
    if (lock_threshold < 0.0f)
9693
5
        lock_threshold = g.IO.MouseDragThreshold;
9694
5
    return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
9695
5
}
9696
9697
bool ImGui::IsMouseDragging(ImGuiMouseButton button, float lock_threshold)
9698
12
{
9699
12
    ImGuiContext& g = *GImGui;
9700
12
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9701
12
    if (!g.IO.MouseDown[button])
9702
7
        return false;
9703
5
    return IsMouseDragPastThreshold(button, lock_threshold);
9704
12
}
9705
9706
ImVec2 ImGui::GetMousePos()
9707
22.0k
{
9708
22.0k
    ImGuiContext& g = *GImGui;
9709
22.0k
    return g.IO.MousePos;
9710
22.0k
}
9711
9712
// This is called TeleportMousePos() and not SetMousePos() to emphasis that setting MousePosPrev will effectively clear mouse delta as well.
9713
// It is expected you only call this if (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos) is set and supported by backend.
9714
void ImGui::TeleportMousePos(const ImVec2& pos)
9715
0
{
9716
0
    ImGuiContext& g = *GImGui;
9717
0
    g.IO.MousePos = g.IO.MousePosPrev = pos;
9718
0
    g.IO.MouseDelta = ImVec2(0.0f, 0.0f);
9719
0
    g.IO.WantSetMousePos = true;
9720
    //IMGUI_DEBUG_LOG_IO("TeleportMousePos: (%.1f,%.1f)\n", io.MousePos.x, io.MousePos.y);
9721
0
}
9722
9723
// NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!
9724
ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
9725
0
{
9726
0
    ImGuiContext& g = *GImGui;
9727
0
    if (g.BeginPopupStack.Size > 0)
9728
0
        return g.OpenPopupStack[g.BeginPopupStack.Size - 1].OpenMousePos;
9729
0
    return g.IO.MousePos;
9730
0
}
9731
9732
// We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position.
9733
bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
9734
419k
{
9735
    // The assert is only to silence a false-positive in XCode Static Analysis.
9736
    // Because GImGui is not dereferenced in every code path, the static analyzer assume that it may be NULL (which it doesn't for other functions).
9737
419k
    IM_ASSERT(GImGui != NULL);
9738
419k
    const float MOUSE_INVALID = -256000.0f;
9739
419k
    ImVec2 p = mouse_pos ? *mouse_pos : GImGui->IO.MousePos;
9740
419k
    return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID;
9741
419k
}
9742
9743
// [WILL OBSOLETE] This was designed for backends, but prefer having backend maintain a mask of held mouse buttons, because upcoming input queue system will make this invalid.
9744
bool ImGui::IsAnyMouseDown()
9745
0
{
9746
0
    ImGuiContext& g = *GImGui;
9747
0
    for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++)
9748
0
        if (g.IO.MouseDown[n])
9749
0
            return true;
9750
0
    return false;
9751
0
}
9752
9753
// Return the delta from the initial clicking position while the mouse button is clicked or was just released.
9754
// This is locked and return 0.0f until the mouse moves past a distance threshold at least once.
9755
// NB: This is only valid if IsMousePosValid(). backends in theory should always keep mouse position valid when dragging even outside the client window.
9756
ImVec2 ImGui::GetMouseDragDelta(ImGuiMouseButton button, float lock_threshold)
9757
0
{
9758
0
    ImGuiContext& g = *GImGui;
9759
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9760
0
    if (lock_threshold < 0.0f)
9761
0
        lock_threshold = g.IO.MouseDragThreshold;
9762
0
    if (g.IO.MouseDown[button] || g.IO.MouseReleased[button])
9763
0
        if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
9764
0
            if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MouseClickedPos[button]))
9765
0
                return g.IO.MousePos - g.IO.MouseClickedPos[button];
9766
0
    return ImVec2(0.0f, 0.0f);
9767
0
}
9768
9769
void ImGui::ResetMouseDragDelta(ImGuiMouseButton button)
9770
0
{
9771
0
    ImGuiContext& g = *GImGui;
9772
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9773
    // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr
9774
0
    g.IO.MouseClickedPos[button] = g.IO.MousePos;
9775
0
}
9776
9777
// Get desired mouse cursor shape.
9778
// Important: this is meant to be used by a platform backend, it is reset in ImGui::NewFrame(),
9779
// updated during the frame, and locked in EndFrame()/Render().
9780
// If you use software rendering by setting io.MouseDrawCursor then Dear ImGui will render those for you
9781
ImGuiMouseCursor ImGui::GetMouseCursor()
9782
0
{
9783
0
    ImGuiContext& g = *GImGui;
9784
0
    return g.MouseCursor;
9785
0
}
9786
9787
void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)
9788
4
{
9789
4
    ImGuiContext& g = *GImGui;
9790
4
    g.MouseCursor = cursor_type;
9791
4
}
9792
9793
static void UpdateAliasKey(ImGuiKey key, bool v, float analog_value)
9794
594k
{
9795
594k
    IM_ASSERT(ImGui::IsAliasKey(key));
9796
594k
    ImGuiKeyData* key_data = ImGui::GetKeyData(key);
9797
594k
    key_data->Down = v;
9798
594k
    key_data->AnalogValue = analog_value;
9799
594k
}
9800
9801
// [Internal] Do not use directly
9802
static ImGuiKeyChord GetMergedModsFromKeys()
9803
169k
{
9804
169k
    ImGuiKeyChord mods = 0;
9805
169k
    if (ImGui::IsKeyDown(ImGuiMod_Ctrl))     { mods |= ImGuiMod_Ctrl; }
9806
169k
    if (ImGui::IsKeyDown(ImGuiMod_Shift))    { mods |= ImGuiMod_Shift; }
9807
169k
    if (ImGui::IsKeyDown(ImGuiMod_Alt))      { mods |= ImGuiMod_Alt; }
9808
169k
    if (ImGui::IsKeyDown(ImGuiMod_Super))    { mods |= ImGuiMod_Super; }
9809
169k
    return mods;
9810
169k
}
9811
9812
static void ImGui::UpdateKeyboardInputs()
9813
84.9k
{
9814
84.9k
    ImGuiContext& g = *GImGui;
9815
84.9k
    ImGuiIO& io = g.IO;
9816
9817
84.9k
    if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard)
9818
0
        io.ClearInputKeys();
9819
9820
    // Import legacy keys or verify they are not used
9821
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9822
    if (io.BackendUsingLegacyKeyArrays == 0)
9823
    {
9824
        // Backend used new io.AddKeyEvent() API: Good! Verify that old arrays are never written to externally.
9825
        for (int n = 0; n < ImGuiKey_LegacyNativeKey_END; n++)
9826
            IM_ASSERT((io.KeysDown[n] == false || IsKeyDown((ImGuiKey)n)) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
9827
    }
9828
    else
9829
    {
9830
        if (g.FrameCount == 0)
9831
            for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
9832
                IM_ASSERT(g.IO.KeyMap[n] == -1 && "Backend is not allowed to write to io.KeyMap[0..511]!");
9833
9834
        // Build reverse KeyMap (Named -> Legacy)
9835
        for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
9836
            if (io.KeyMap[n] != -1)
9837
            {
9838
                IM_ASSERT(IsLegacyKey((ImGuiKey)io.KeyMap[n]));
9839
                io.KeyMap[io.KeyMap[n]] = n;
9840
            }
9841
9842
        // Import legacy keys into new ones
9843
        for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
9844
            if (io.KeysDown[n] || io.BackendUsingLegacyKeyArrays == 1)
9845
            {
9846
                const ImGuiKey key = (ImGuiKey)(io.KeyMap[n] != -1 ? io.KeyMap[n] : n);
9847
                IM_ASSERT(io.KeyMap[n] == -1 || IsNamedKey(key));
9848
                io.KeysData[key].Down = io.KeysDown[n];
9849
                if (key != n)
9850
                    io.KeysDown[key] = io.KeysDown[n]; // Allow legacy code using io.KeysDown[GetKeyIndex()] with old backends
9851
                io.BackendUsingLegacyKeyArrays = 1;
9852
            }
9853
        if (io.BackendUsingLegacyKeyArrays == 1)
9854
        {
9855
            GetKeyData(ImGuiMod_Ctrl)->Down = io.KeyCtrl;
9856
            GetKeyData(ImGuiMod_Shift)->Down = io.KeyShift;
9857
            GetKeyData(ImGuiMod_Alt)->Down = io.KeyAlt;
9858
            GetKeyData(ImGuiMod_Super)->Down = io.KeySuper;
9859
        }
9860
    }
9861
#endif
9862
9863
    // Import legacy ImGuiNavInput_ io inputs and convert to gamepad keys
9864
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9865
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
9866
    if (io.BackendUsingLegacyNavInputArray && nav_gamepad_active)
9867
    {
9868
        #define MAP_LEGACY_NAV_INPUT_TO_KEY1(_KEY, _NAV1)           do { io.KeysData[_KEY].Down = (io.NavInputs[_NAV1] > 0.0f); io.KeysData[_KEY].AnalogValue = io.NavInputs[_NAV1]; } while (0)
9869
        #define MAP_LEGACY_NAV_INPUT_TO_KEY2(_KEY, _NAV1, _NAV2)    do { io.KeysData[_KEY].Down = (io.NavInputs[_NAV1] > 0.0f) || (io.NavInputs[_NAV2] > 0.0f); io.KeysData[_KEY].AnalogValue = ImMax(io.NavInputs[_NAV1], io.NavInputs[_NAV2]); } while (0)
9870
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceDown, ImGuiNavInput_Activate);
9871
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceRight, ImGuiNavInput_Cancel);
9872
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceLeft, ImGuiNavInput_Menu);
9873
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceUp, ImGuiNavInput_Input);
9874
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadLeft, ImGuiNavInput_DpadLeft);
9875
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadRight, ImGuiNavInput_DpadRight);
9876
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadUp, ImGuiNavInput_DpadUp);
9877
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadDown, ImGuiNavInput_DpadDown);
9878
        MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadL1, ImGuiNavInput_FocusPrev, ImGuiNavInput_TweakSlow);
9879
        MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadR1, ImGuiNavInput_FocusNext, ImGuiNavInput_TweakFast);
9880
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickLeft, ImGuiNavInput_LStickLeft);
9881
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickRight, ImGuiNavInput_LStickRight);
9882
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickUp, ImGuiNavInput_LStickUp);
9883
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickDown, ImGuiNavInput_LStickDown);
9884
        #undef NAV_MAP_KEY
9885
    }
9886
#endif
9887
9888
    // Update aliases
9889
509k
    for (int n = 0; n < ImGuiMouseButton_COUNT; n++)
9890
424k
        UpdateAliasKey(MouseButtonToKey(n), io.MouseDown[n], io.MouseDown[n] ? 1.0f : 0.0f);
9891
84.9k
    UpdateAliasKey(ImGuiKey_MouseWheelX, io.MouseWheelH != 0.0f, io.MouseWheelH);
9892
84.9k
    UpdateAliasKey(ImGuiKey_MouseWheelY, io.MouseWheel != 0.0f, io.MouseWheel);
9893
9894
    // Synchronize io.KeyMods and io.KeyCtrl/io.KeyShift/etc. values.
9895
    // - New backends (1.87+): send io.AddKeyEvent(ImGuiMod_XXX) ->                                      -> (here) deriving io.KeyMods + io.KeyXXX from key array.
9896
    // - Legacy backends:      set io.KeyXXX bools               -> (above) set key array from io.KeyXXX -> (here) deriving io.KeyMods + io.KeyXXX from key array.
9897
    // So with legacy backends the 4 values will do a unnecessary back-and-forth but it makes the code simpler and future facing.
9898
84.9k
    const ImGuiKeyChord prev_key_mods = io.KeyMods;
9899
84.9k
    io.KeyMods = GetMergedModsFromKeys();
9900
84.9k
    io.KeyCtrl = (io.KeyMods & ImGuiMod_Ctrl) != 0;
9901
84.9k
    io.KeyShift = (io.KeyMods & ImGuiMod_Shift) != 0;
9902
84.9k
    io.KeyAlt = (io.KeyMods & ImGuiMod_Alt) != 0;
9903
84.9k
    io.KeySuper = (io.KeyMods & ImGuiMod_Super) != 0;
9904
84.9k
    if (prev_key_mods != io.KeyMods)
9905
0
        g.LastKeyModsChangeTime = g.Time;
9906
84.9k
    if (prev_key_mods != io.KeyMods && prev_key_mods == 0)
9907
0
        g.LastKeyModsChangeFromNoneTime = g.Time;
9908
9909
    // Clear gamepad data if disabled
9910
84.9k
    if ((io.BackendFlags & ImGuiBackendFlags_HasGamepad) == 0)
9911
2.12M
        for (int i = ImGuiKey_Gamepad_BEGIN; i < ImGuiKey_Gamepad_END; i++)
9912
2.03M
        {
9913
2.03M
            io.KeysData[i - ImGuiKey_KeysData_OFFSET].Down = false;
9914
2.03M
            io.KeysData[i - ImGuiKey_KeysData_OFFSET].AnalogValue = 0.0f;
9915
2.03M
        }
9916
9917
    // Update keys
9918
13.1M
    for (int i = 0; i < ImGuiKey_KeysData_SIZE; i++)
9919
13.0M
    {
9920
13.0M
        ImGuiKeyData* key_data = &io.KeysData[i];
9921
13.0M
        key_data->DownDurationPrev = key_data->DownDuration;
9922
13.0M
        key_data->DownDuration = key_data->Down ? (key_data->DownDuration < 0.0f ? 0.0f : key_data->DownDuration + io.DeltaTime) : -1.0f;
9923
13.0M
        if (key_data->DownDuration == 0.0f)
9924
9.92k
        {
9925
9.92k
            ImGuiKey key = (ImGuiKey)(ImGuiKey_KeysData_OFFSET + i);
9926
9.92k
            if (IsKeyboardKey(key))
9927
4.22k
                g.LastKeyboardKeyPressTime = g.Time;
9928
5.69k
            else if (key == ImGuiKey_ReservedForModCtrl || key == ImGuiKey_ReservedForModShift || key == ImGuiKey_ReservedForModAlt || key == ImGuiKey_ReservedForModSuper)
9929
0
                g.LastKeyboardKeyPressTime = g.Time;
9930
9.92k
        }
9931
13.0M
    }
9932
9933
    // Update keys/input owner (named keys only): one entry per key
9934
13.1M
    for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
9935
13.0M
    {
9936
13.0M
        ImGuiKeyData* key_data = &io.KeysData[key - ImGuiKey_KeysData_OFFSET];
9937
13.0M
        ImGuiKeyOwnerData* owner_data = &g.KeysOwnerData[key - ImGuiKey_NamedKey_BEGIN];
9938
13.0M
        owner_data->OwnerCurr = owner_data->OwnerNext;
9939
13.0M
        if (!key_data->Down) // Important: ownership is released on the frame after a release. Ensure a 'MouseDown -> CloseWindow -> MouseUp' chain doesn't lead to someone else seeing the MouseUp.
9940
12.8M
            owner_data->OwnerNext = ImGuiKeyOwner_NoOwner;
9941
13.0M
        owner_data->LockThisFrame = owner_data->LockUntilRelease = owner_data->LockUntilRelease && key_data->Down;  // Clear LockUntilRelease when key is not Down anymore
9942
13.0M
    }
9943
9944
    // Update key routing (for e.g. shortcuts)
9945
84.9k
    UpdateKeyRoutingTable(&g.KeysRoutingTable);
9946
84.9k
}
9947
9948
static void ImGui::UpdateMouseInputs()
9949
84.9k
{
9950
84.9k
    ImGuiContext& g = *GImGui;
9951
84.9k
    ImGuiIO& io = g.IO;
9952
9953
    // Mouse Wheel swapping flag
9954
    // As a standard behavior holding SHIFT while using Vertical Mouse Wheel triggers Horizontal scroll instead
9955
    // - We avoid doing it on OSX as it the OS input layer handles this already.
9956
    // - FIXME: However this means when running on OSX over Emscripten, Shift+WheelY will incur two swapping (1 in OS, 1 here), canceling the feature.
9957
    // - FIXME: When we can distinguish e.g. touchpad scroll events from mouse ones, we'll set this accordingly based on input source.
9958
84.9k
    io.MouseWheelRequestAxisSwap = io.KeyShift && !io.ConfigMacOSXBehaviors;
9959
9960
    // Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well)
9961
84.9k
    if (IsMousePosValid(&io.MousePos))
9962
70.6k
        io.MousePos = g.MouseLastValidPos = ImFloor(io.MousePos);
9963
9964
    // If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) we cancel out movement in MouseDelta
9965
84.9k
    if (IsMousePosValid(&io.MousePos) && IsMousePosValid(&io.MousePosPrev))
9966
70.5k
        io.MouseDelta = io.MousePos - io.MousePosPrev;
9967
14.3k
    else
9968
14.3k
        io.MouseDelta = ImVec2(0.0f, 0.0f);
9969
9970
    // Update stationary timer.
9971
    // FIXME: May need to rework again to have some tolerance for occasional small movement, while being functional on high-framerates.
9972
84.9k
    const float mouse_stationary_threshold = (io.MouseSource == ImGuiMouseSource_Mouse) ? 2.0f : 3.0f; // Slightly higher threshold for ImGuiMouseSource_TouchScreen/ImGuiMouseSource_Pen, may need rework.
9973
84.9k
    const bool mouse_stationary = (ImLengthSqr(io.MouseDelta) <= mouse_stationary_threshold * mouse_stationary_threshold);
9974
84.9k
    g.MouseStationaryTimer = mouse_stationary ? (g.MouseStationaryTimer + io.DeltaTime) : 0.0f;
9975
    //IMGUI_DEBUG_LOG("%.4f\n", g.MouseStationaryTimer);
9976
9977
    // If mouse moved we re-enable mouse hovering in case it was disabled by gamepad/keyboard. In theory should use a >0.0f threshold but would need to reset in everywhere we set this to true.
9978
84.9k
    if (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)
9979
1.38k
        g.NavDisableMouseHover = false;
9980
9981
509k
    for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
9982
424k
    {
9983
424k
        io.MouseClicked[i] = io.MouseDown[i] && io.MouseDownDuration[i] < 0.0f;
9984
424k
        io.MouseClickedCount[i] = 0; // Will be filled below
9985
424k
        io.MouseReleased[i] = !io.MouseDown[i] && io.MouseDownDuration[i] >= 0.0f;
9986
424k
        io.MouseDownDurationPrev[i] = io.MouseDownDuration[i];
9987
424k
        io.MouseDownDuration[i] = io.MouseDown[i] ? (io.MouseDownDuration[i] < 0.0f ? 0.0f : io.MouseDownDuration[i] + io.DeltaTime) : -1.0f;
9988
424k
        if (io.MouseClicked[i])
9989
4.14k
        {
9990
4.14k
            bool is_repeated_click = false;
9991
4.14k
            if ((float)(g.Time - io.MouseClickedTime[i]) < io.MouseDoubleClickTime)
9992
3.51k
            {
9993
3.51k
                ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
9994
3.51k
                if (ImLengthSqr(delta_from_click_pos) < io.MouseDoubleClickMaxDist * io.MouseDoubleClickMaxDist)
9995
3.07k
                    is_repeated_click = true;
9996
3.51k
            }
9997
4.14k
            if (is_repeated_click)
9998
3.07k
                io.MouseClickedLastCount[i]++;
9999
1.07k
            else
10000
1.07k
                io.MouseClickedLastCount[i] = 1;
10001
4.14k
            io.MouseClickedTime[i] = g.Time;
10002
4.14k
            io.MouseClickedPos[i] = io.MousePos;
10003
4.14k
            io.MouseClickedCount[i] = io.MouseClickedLastCount[i];
10004
4.14k
            io.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f);
10005
4.14k
            io.MouseDragMaxDistanceSqr[i] = 0.0f;
10006
4.14k
        }
10007
420k
        else if (io.MouseDown[i])
10008
151k
        {
10009
            // Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold
10010
151k
            ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
10011
151k
            io.MouseDragMaxDistanceSqr[i] = ImMax(io.MouseDragMaxDistanceSqr[i], ImLengthSqr(delta_from_click_pos));
10012
151k
            io.MouseDragMaxDistanceAbs[i].x = ImMax(io.MouseDragMaxDistanceAbs[i].x, delta_from_click_pos.x < 0.0f ? -delta_from_click_pos.x : delta_from_click_pos.x);
10013
151k
            io.MouseDragMaxDistanceAbs[i].y = ImMax(io.MouseDragMaxDistanceAbs[i].y, delta_from_click_pos.y < 0.0f ? -delta_from_click_pos.y : delta_from_click_pos.y);
10014
151k
        }
10015
10016
        // We provide io.MouseDoubleClicked[] as a legacy service
10017
424k
        io.MouseDoubleClicked[i] = (io.MouseClickedCount[i] == 2);
10018
10019
        // Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation
10020
424k
        if (io.MouseClicked[i])
10021
4.14k
            g.NavDisableMouseHover = false;
10022
424k
    }
10023
84.9k
}
10024
10025
static void LockWheelingWindow(ImGuiWindow* window, float wheel_amount)
10026
0
{
10027
0
    ImGuiContext& g = *GImGui;
10028
0
    if (window)
10029
0
        g.WheelingWindowReleaseTimer = ImMin(g.WheelingWindowReleaseTimer + ImAbs(wheel_amount) * WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER, WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER);
10030
0
    else
10031
0
        g.WheelingWindowReleaseTimer = 0.0f;
10032
0
    if (g.WheelingWindow == window)
10033
0
        return;
10034
0
    IMGUI_DEBUG_LOG_IO("[io] LockWheelingWindow() \"%s\"\n", window ? window->Name : "NULL");
10035
0
    g.WheelingWindow = window;
10036
0
    g.WheelingWindowRefMousePos = g.IO.MousePos;
10037
0
    if (window == NULL)
10038
0
    {
10039
0
        g.WheelingWindowStartFrame = -1;
10040
0
        g.WheelingAxisAvg = ImVec2(0.0f, 0.0f);
10041
0
    }
10042
0
}
10043
10044
static ImGuiWindow* FindBestWheelingWindow(const ImVec2& wheel)
10045
2
{
10046
    // For each axis, find window in the hierarchy that may want to use scrolling
10047
2
    ImGuiContext& g = *GImGui;
10048
2
    ImGuiWindow* windows[2] = { NULL, NULL };
10049
6
    for (int axis = 0; axis < 2; axis++)
10050
4
        if (wheel[axis] != 0.0f)
10051
3
            for (ImGuiWindow* window = windows[axis] = g.HoveredWindow; window->Flags & ImGuiWindowFlags_ChildWindow; window = windows[axis] = window->ParentWindow)
10052
0
            {
10053
                // Bubble up into parent window if:
10054
                // - a child window doesn't allow any scrolling.
10055
                // - a child window has the ImGuiWindowFlags_NoScrollWithMouse flag.
10056
                //// - a child window doesn't need scrolling because it is already at the edge for the direction we are going in (FIXME-WIP)
10057
0
                const bool has_scrolling = (window->ScrollMax[axis] != 0.0f);
10058
0
                const bool inputs_disabled = (window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs);
10059
                //const bool scrolling_past_limits = (wheel_v < 0.0f) ? (window->Scroll[axis] <= 0.0f) : (window->Scroll[axis] >= window->ScrollMax[axis]);
10060
0
                if (has_scrolling && !inputs_disabled) // && !scrolling_past_limits)
10061
0
                    break; // select this window
10062
0
            }
10063
2
    if (windows[0] == NULL && windows[1] == NULL)
10064
0
        return NULL;
10065
10066
    // If there's only one window or only one axis then there's no ambiguity
10067
2
    if (windows[0] == windows[1] || windows[0] == NULL || windows[1] == NULL)
10068
2
        return windows[1] ? windows[1] : windows[0];
10069
10070
    // If candidate are different windows we need to decide which one to prioritize
10071
    // - First frame: only find a winner if one axis is zero.
10072
    // - Subsequent frames: only find a winner when one is more than the other.
10073
0
    if (g.WheelingWindowStartFrame == -1)
10074
0
        g.WheelingWindowStartFrame = g.FrameCount;
10075
0
    if ((g.WheelingWindowStartFrame == g.FrameCount && wheel.x != 0.0f && wheel.y != 0.0f) || (g.WheelingAxisAvg.x == g.WheelingAxisAvg.y))
10076
0
    {
10077
0
        g.WheelingWindowWheelRemainder = wheel;
10078
0
        return NULL;
10079
0
    }
10080
0
    return (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? windows[0] : windows[1];
10081
0
}
10082
10083
// Called by NewFrame()
10084
void ImGui::UpdateMouseWheel()
10085
84.9k
{
10086
    // Reset the locked window if we move the mouse or after the timer elapses.
10087
    // FIXME: Ideally we could refactor to have one timer for "changing window w/ same axis" and a shorter timer for "changing window or axis w/ other axis" (#3795)
10088
84.9k
    ImGuiContext& g = *GImGui;
10089
84.9k
    if (g.WheelingWindow != NULL)
10090
0
    {
10091
0
        g.WheelingWindowReleaseTimer -= g.IO.DeltaTime;
10092
0
        if (IsMousePosValid() && ImLengthSqr(g.IO.MousePos - g.WheelingWindowRefMousePos) > g.IO.MouseDragThreshold * g.IO.MouseDragThreshold)
10093
0
            g.WheelingWindowReleaseTimer = 0.0f;
10094
0
        if (g.WheelingWindowReleaseTimer <= 0.0f)
10095
0
            LockWheelingWindow(NULL, 0.0f);
10096
0
    }
10097
10098
84.9k
    ImVec2 wheel;
10099
84.9k
    wheel.x = TestKeyOwner(ImGuiKey_MouseWheelX, ImGuiKeyOwner_NoOwner) ? g.IO.MouseWheelH : 0.0f;
10100
84.9k
    wheel.y = TestKeyOwner(ImGuiKey_MouseWheelY, ImGuiKeyOwner_NoOwner) ? g.IO.MouseWheel : 0.0f;
10101
10102
    //IMGUI_DEBUG_LOG("MouseWheel X:%.3f Y:%.3f\n", wheel_x, wheel_y);
10103
84.9k
    ImGuiWindow* mouse_window = g.WheelingWindow ? g.WheelingWindow : g.HoveredWindow;
10104
84.9k
    if (!mouse_window || mouse_window->Collapsed)
10105
84.6k
        return;
10106
10107
    // Zoom / Scale window
10108
    // FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned.
10109
329
    if (wheel.y != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
10110
0
    {
10111
0
        LockWheelingWindow(mouse_window, wheel.y);
10112
0
        ImGuiWindow* window = mouse_window;
10113
0
        const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
10114
0
        const float scale = new_font_scale / window->FontWindowScale;
10115
0
        window->FontWindowScale = new_font_scale;
10116
0
        if (window == window->RootWindow)
10117
0
        {
10118
0
            const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
10119
0
            SetWindowPos(window, window->Pos + offset, 0);
10120
0
            window->Size = ImTrunc(window->Size * scale);
10121
0
            window->SizeFull = ImTrunc(window->SizeFull * scale);
10122
0
        }
10123
0
        return;
10124
0
    }
10125
329
    if (g.IO.KeyCtrl)
10126
0
        return;
10127
10128
    // Mouse wheel scrolling
10129
    // Read about io.MouseWheelRequestAxisSwap and its issue on Mac+Emscripten in UpdateMouseInputs()
10130
329
    if (g.IO.MouseWheelRequestAxisSwap)
10131
0
        wheel = ImVec2(wheel.y, 0.0f);
10132
10133
    // Maintain a rough average of moving magnitude on both axises
10134
    // FIXME: should by based on wall clock time rather than frame-counter
10135
329
    g.WheelingAxisAvg.x = ImExponentialMovingAverage(g.WheelingAxisAvg.x, ImAbs(wheel.x), 30);
10136
329
    g.WheelingAxisAvg.y = ImExponentialMovingAverage(g.WheelingAxisAvg.y, ImAbs(wheel.y), 30);
10137
10138
    // In the rare situation where FindBestWheelingWindow() had to defer first frame of wheeling due to ambiguous main axis, reinject it now.
10139
329
    wheel += g.WheelingWindowWheelRemainder;
10140
329
    g.WheelingWindowWheelRemainder = ImVec2(0.0f, 0.0f);
10141
329
    if (wheel.x == 0.0f && wheel.y == 0.0f)
10142
327
        return;
10143
10144
    // Mouse wheel scrolling: find target and apply
10145
    // - don't renew lock if axis doesn't apply on the window.
10146
    // - select a main axis when both axises are being moved.
10147
2
    if (ImGuiWindow* window = (g.WheelingWindow ? g.WheelingWindow : FindBestWheelingWindow(wheel)))
10148
2
        if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
10149
2
        {
10150
2
            bool do_scroll[2] = { wheel.x != 0.0f && window->ScrollMax.x != 0.0f, wheel.y != 0.0f && window->ScrollMax.y != 0.0f };
10151
2
            if (do_scroll[ImGuiAxis_X] && do_scroll[ImGuiAxis_Y])
10152
0
                do_scroll[(g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? ImGuiAxis_Y : ImGuiAxis_X] = false;
10153
2
            if (do_scroll[ImGuiAxis_X])
10154
0
            {
10155
0
                LockWheelingWindow(window, wheel.x);
10156
0
                float max_step = window->InnerRect.GetWidth() * 0.67f;
10157
0
                float scroll_step = ImTrunc(ImMin(2 * window->CalcFontSize(), max_step));
10158
0
                SetScrollX(window, window->Scroll.x - wheel.x * scroll_step);
10159
0
                g.WheelingWindowScrolledFrame = g.FrameCount;
10160
0
            }
10161
2
            if (do_scroll[ImGuiAxis_Y])
10162
0
            {
10163
0
                LockWheelingWindow(window, wheel.y);
10164
0
                float max_step = window->InnerRect.GetHeight() * 0.67f;
10165
0
                float scroll_step = ImTrunc(ImMin(5 * window->CalcFontSize(), max_step));
10166
0
                SetScrollY(window, window->Scroll.y - wheel.y * scroll_step);
10167
0
                g.WheelingWindowScrolledFrame = g.FrameCount;
10168
0
            }
10169
2
        }
10170
2
}
10171
10172
void ImGui::SetNextFrameWantCaptureKeyboard(bool want_capture_keyboard)
10173
0
{
10174
0
    ImGuiContext& g = *GImGui;
10175
0
    g.WantCaptureKeyboardNextFrame = want_capture_keyboard ? 1 : 0;
10176
0
}
10177
10178
void ImGui::SetNextFrameWantCaptureMouse(bool want_capture_mouse)
10179
0
{
10180
0
    ImGuiContext& g = *GImGui;
10181
0
    g.WantCaptureMouseNextFrame = want_capture_mouse ? 1 : 0;
10182
0
}
10183
10184
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
10185
static const char* GetInputSourceName(ImGuiInputSource source)
10186
0
{
10187
0
    const char* input_source_names[] = { "None", "Mouse", "Keyboard", "Gamepad" };
10188
0
    IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT && source >= 0 && source < ImGuiInputSource_COUNT);
10189
0
    return input_source_names[source];
10190
0
}
10191
static const char* GetMouseSourceName(ImGuiMouseSource source)
10192
0
{
10193
0
    const char* mouse_source_names[] = { "Mouse", "TouchScreen", "Pen" };
10194
0
    IM_ASSERT(IM_ARRAYSIZE(mouse_source_names) == ImGuiMouseSource_COUNT && source >= 0 && source < ImGuiMouseSource_COUNT);
10195
0
    return mouse_source_names[source];
10196
0
}
10197
static void DebugPrintInputEvent(const char* prefix, const ImGuiInputEvent* e)
10198
0
{
10199
0
    ImGuiContext& g = *GImGui;
10200
0
    if (e->Type == ImGuiInputEventType_MousePos)    { if (e->MousePos.PosX == -FLT_MAX && e->MousePos.PosY == -FLT_MAX) IMGUI_DEBUG_LOG_IO("[io] %s: MousePos (-FLT_MAX, -FLT_MAX)\n", prefix); else IMGUI_DEBUG_LOG_IO("[io] %s: MousePos (%.1f, %.1f) (%s)\n", prefix, e->MousePos.PosX, e->MousePos.PosY, GetMouseSourceName(e->MousePos.MouseSource)); return; }
10201
0
    if (e->Type == ImGuiInputEventType_MouseButton) { IMGUI_DEBUG_LOG_IO("[io] %s: MouseButton %d %s (%s)\n", prefix, e->MouseButton.Button, e->MouseButton.Down ? "Down" : "Up", GetMouseSourceName(e->MouseButton.MouseSource)); return; }
10202
0
    if (e->Type == ImGuiInputEventType_MouseWheel)  { IMGUI_DEBUG_LOG_IO("[io] %s: MouseWheel (%.3f, %.3f) (%s)\n", prefix, e->MouseWheel.WheelX, e->MouseWheel.WheelY, GetMouseSourceName(e->MouseWheel.MouseSource)); return; }
10203
0
    if (e->Type == ImGuiInputEventType_MouseViewport){IMGUI_DEBUG_LOG_IO("[io] %s: MouseViewport (0x%08X)\n", prefix, e->MouseViewport.HoveredViewportID); return; }
10204
0
    if (e->Type == ImGuiInputEventType_Key)         { IMGUI_DEBUG_LOG_IO("[io] %s: Key \"%s\" %s\n", prefix, ImGui::GetKeyName(e->Key.Key), e->Key.Down ? "Down" : "Up"); return; }
10205
0
    if (e->Type == ImGuiInputEventType_Text)        { IMGUI_DEBUG_LOG_IO("[io] %s: Text: %c (U+%08X)\n", prefix, e->Text.Char, e->Text.Char); return; }
10206
0
    if (e->Type == ImGuiInputEventType_Focus)       { IMGUI_DEBUG_LOG_IO("[io] %s: AppFocused %d\n", prefix, e->AppFocused.Focused); return; }
10207
0
}
10208
#endif
10209
10210
// Process input queue
10211
// We always call this with the value of 'bool g.IO.ConfigInputTrickleEventQueue'.
10212
// - trickle_fast_inputs = false : process all events, turn into flattened input state (e.g. successive down/up/down/up will be lost)
10213
// - trickle_fast_inputs = true  : process as many events as possible (successive down/up/down/up will be trickled over several frames so nothing is lost) (new feature in 1.87)
10214
void ImGui::UpdateInputEvents(bool trickle_fast_inputs)
10215
84.9k
{
10216
84.9k
    ImGuiContext& g = *GImGui;
10217
84.9k
    ImGuiIO& io = g.IO;
10218
10219
    // Only trickle chars<>key when working with InputText()
10220
    // FIXME: InputText() could parse event trail?
10221
    // FIXME: Could specialize chars<>keys trickling rules for control keys (those not typically associated to characters)
10222
84.9k
    const bool trickle_interleaved_keys_and_text = (trickle_fast_inputs && g.WantTextInputNextFrame == 1);
10223
10224
84.9k
    bool mouse_moved = false, mouse_wheeled = false, key_changed = false, text_inputted = false;
10225
84.9k
    int  mouse_button_changed = 0x00;
10226
84.9k
    ImBitArray<ImGuiKey_KeysData_SIZE> key_changed_mask;
10227
10228
84.9k
    int event_n = 0;
10229
109k
    for (; event_n < g.InputEventsQueue.Size; event_n++)
10230
33.2k
    {
10231
33.2k
        ImGuiInputEvent* e = &g.InputEventsQueue[event_n];
10232
33.2k
        if (e->Type == ImGuiInputEventType_MousePos)
10233
2.52k
        {
10234
2.52k
            if (g.IO.WantSetMousePos)
10235
0
                continue;
10236
            // Trickling Rule: Stop processing queued events if we already handled a mouse button change
10237
2.52k
            ImVec2 event_pos(e->MousePos.PosX, e->MousePos.PosY);
10238
2.52k
            if (trickle_fast_inputs && (mouse_button_changed != 0 || mouse_wheeled || key_changed || text_inputted))
10239
585
                break;
10240
1.94k
            io.MousePos = event_pos;
10241
1.94k
            io.MouseSource = e->MousePos.MouseSource;
10242
1.94k
            mouse_moved = true;
10243
1.94k
        }
10244
30.7k
        else if (e->Type == ImGuiInputEventType_MouseButton)
10245
12.5k
        {
10246
            // Trickling Rule: Stop processing queued events if we got multiple action on the same button
10247
12.5k
            const ImGuiMouseButton button = e->MouseButton.Button;
10248
12.5k
            IM_ASSERT(button >= 0 && button < ImGuiMouseButton_COUNT);
10249
12.5k
            if (trickle_fast_inputs && ((mouse_button_changed & (1 << button)) || mouse_wheeled))
10250
4.43k
                break;
10251
8.13k
            if (trickle_fast_inputs && e->MouseButton.MouseSource == ImGuiMouseSource_TouchScreen && mouse_moved) // #2702: TouchScreen have no initial hover.
10252
0
                break;
10253
8.13k
            io.MouseDown[button] = e->MouseButton.Down;
10254
8.13k
            io.MouseSource = e->MouseButton.MouseSource;
10255
8.13k
            mouse_button_changed |= (1 << button);
10256
8.13k
        }
10257
18.1k
        else if (e->Type == ImGuiInputEventType_MouseWheel)
10258
2.23k
        {
10259
            // Trickling Rule: Stop processing queued events if we got multiple action on the event
10260
2.23k
            if (trickle_fast_inputs && (mouse_moved || mouse_button_changed != 0))
10261
468
                break;
10262
1.77k
            io.MouseWheelH += e->MouseWheel.WheelX;
10263
1.77k
            io.MouseWheel += e->MouseWheel.WheelY;
10264
1.77k
            io.MouseSource = e->MouseWheel.MouseSource;
10265
1.77k
            mouse_wheeled = true;
10266
1.77k
        }
10267
15.9k
        else if (e->Type == ImGuiInputEventType_MouseViewport)
10268
0
        {
10269
0
            io.MouseHoveredViewport = e->MouseViewport.HoveredViewportID;
10270
0
        }
10271
15.9k
        else if (e->Type == ImGuiInputEventType_Key)
10272
7.72k
        {
10273
            // Trickling Rule: Stop processing queued events if we got multiple action on the same button
10274
7.72k
            if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard)
10275
0
                continue;
10276
7.72k
            ImGuiKey key = e->Key.Key;
10277
7.72k
            IM_ASSERT(key != ImGuiKey_None);
10278
7.72k
            ImGuiKeyData* key_data = GetKeyData(key);
10279
7.72k
            const int key_data_index = (int)(key_data - g.IO.KeysData);
10280
7.72k
            if (trickle_fast_inputs && key_data->Down != e->Key.Down && (key_changed_mask.TestBit(key_data_index) || text_inputted || mouse_button_changed != 0))
10281
1.82k
                break;
10282
5.89k
            key_data->Down = e->Key.Down;
10283
5.89k
            key_data->AnalogValue = e->Key.AnalogValue;
10284
5.89k
            key_changed = true;
10285
5.89k
            key_changed_mask.SetBit(key_data_index);
10286
10287
            // Allow legacy code using io.KeysDown[GetKeyIndex()] with new backends
10288
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
10289
            io.KeysDown[key_data_index] = key_data->Down;
10290
            if (io.KeyMap[key_data_index] != -1)
10291
                io.KeysDown[io.KeyMap[key_data_index]] = key_data->Down;
10292
#endif
10293
5.89k
        }
10294
8.21k
        else if (e->Type == ImGuiInputEventType_Text)
10295
6.89k
        {
10296
6.89k
            if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard)
10297
0
                continue;
10298
            // Trickling Rule: Stop processing queued events if keys/mouse have been interacted with
10299
6.89k
            if (trickle_fast_inputs && ((key_changed && trickle_interleaved_keys_and_text) || mouse_button_changed != 0 || mouse_moved || mouse_wheeled))
10300
975
                break;
10301
5.91k
            unsigned int c = e->Text.Char;
10302
5.91k
            io.InputQueueCharacters.push_back(c <= IM_UNICODE_CODEPOINT_MAX ? (ImWchar)c : IM_UNICODE_CODEPOINT_INVALID);
10303
5.91k
            if (trickle_interleaved_keys_and_text)
10304
0
                text_inputted = true;
10305
5.91k
        }
10306
1.32k
        else if (e->Type == ImGuiInputEventType_Focus)
10307
1.32k
        {
10308
            // We intentionally overwrite this and process in NewFrame(), in order to give a chance
10309
            // to multi-viewports backends to queue AddFocusEvent(false) + AddFocusEvent(true) in same frame.
10310
1.32k
            const bool focus_lost = !e->AppFocused.Focused;
10311
1.32k
            io.AppFocusLost = focus_lost;
10312
1.32k
        }
10313
0
        else
10314
0
        {
10315
0
            IM_ASSERT(0 && "Unknown event!");
10316
0
        }
10317
33.2k
    }
10318
10319
    // Record trail (for domain-specific applications wanting to access a precise trail)
10320
    //if (event_n != 0) IMGUI_DEBUG_LOG_IO("Processed: %d / Remaining: %d\n", event_n, g.InputEventsQueue.Size - event_n);
10321
109k
    for (int n = 0; n < event_n; n++)
10322
24.9k
        g.InputEventsTrail.push_back(g.InputEventsQueue[n]);
10323
10324
    // [DEBUG]
10325
84.9k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
10326
84.9k
    if (event_n != 0 && (g.DebugLogFlags & ImGuiDebugLogFlags_EventIO))
10327
0
        for (int n = 0; n < g.InputEventsQueue.Size; n++)
10328
0
            DebugPrintInputEvent(n < event_n ? "Processed" : "Remaining", &g.InputEventsQueue[n]);
10329
84.9k
#endif
10330
10331
    // Remaining events will be processed on the next frame
10332
84.9k
    if (event_n == g.InputEventsQueue.Size)
10333
76.6k
        g.InputEventsQueue.resize(0);
10334
8.28k
    else
10335
8.28k
        g.InputEventsQueue.erase(g.InputEventsQueue.Data, g.InputEventsQueue.Data + event_n);
10336
10337
    // Clear buttons state when focus is lost
10338
    // - this is useful so e.g. releasing Alt after focus loss on Alt-Tab doesn't trigger the Alt menu toggle.
10339
    // - we clear in EndFrame() and not now in order allow application/user code polling this flag
10340
    //   (e.g. custom backend may want to clear additional data, custom widgets may want to react with a "canceling" event).
10341
84.9k
    if (g.IO.AppFocusLost)
10342
958
    {
10343
958
        g.IO.ClearInputKeys();
10344
958
        g.IO.ClearInputMouse();
10345
958
    }
10346
84.9k
}
10347
10348
ImGuiID ImGui::GetKeyOwner(ImGuiKey key)
10349
0
{
10350
0
    if (!IsNamedKeyOrMod(key))
10351
0
        return ImGuiKeyOwner_NoOwner;
10352
10353
0
    ImGuiContext& g = *GImGui;
10354
0
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
10355
0
    ImGuiID owner_id = owner_data->OwnerCurr;
10356
10357
0
    if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
10358
0
        if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
10359
0
            return ImGuiKeyOwner_NoOwner;
10360
10361
0
    return owner_id;
10362
0
}
10363
10364
// TestKeyOwner(..., ID)   : (owner == None || owner == ID)
10365
// TestKeyOwner(..., None) : (owner == None)
10366
// TestKeyOwner(..., Any)  : no owner test
10367
// All paths are also testing for key not being locked, for the rare cases that key have been locked with using ImGuiInputFlags_LockXXX flags.
10368
bool ImGui::TestKeyOwner(ImGuiKey key, ImGuiID owner_id)
10369
217k
{
10370
217k
    if (!IsNamedKeyOrMod(key))
10371
0
        return true;
10372
10373
217k
    ImGuiContext& g = *GImGui;
10374
217k
    if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
10375
0
        if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
10376
0
            return false;
10377
10378
217k
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
10379
217k
    if (owner_id == ImGuiKeyOwner_Any)
10380
35.7k
        return (owner_data->LockThisFrame == false);
10381
10382
    // Note: SetKeyOwner() sets OwnerCurr. It is not strictly required for most mouse routing overlap (because of ActiveId/HoveredId
10383
    // are acting as filter before this has a chance to filter), but sane as soon as user tries to look into things.
10384
    // Setting OwnerCurr in SetKeyOwner() is more consistent than testing OwnerNext here: would be inconsistent with getter and other functions.
10385
181k
    if (owner_data->OwnerCurr != owner_id)
10386
1
    {
10387
1
        if (owner_data->LockThisFrame)
10388
0
            return false;
10389
1
        if (owner_data->OwnerCurr != ImGuiKeyOwner_NoOwner)
10390
0
            return false;
10391
1
    }
10392
10393
181k
    return true;
10394
181k
}
10395
10396
// _LockXXX flags are useful to lock keys away from code which is not input-owner aware.
10397
// When using _LockXXX flags, you can use ImGuiKeyOwner_Any to lock keys from everyone.
10398
// - SetKeyOwner(..., None)              : clears owner
10399
// - SetKeyOwner(..., Any, !Lock)        : illegal (assert)
10400
// - SetKeyOwner(..., Any or None, Lock) : set lock
10401
void ImGui::SetKeyOwner(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags)
10402
1
{
10403
1
    ImGuiContext& g = *GImGui;
10404
1
    IM_ASSERT(IsNamedKeyOrMod(key) && (owner_id != ImGuiKeyOwner_Any || (flags & (ImGuiInputFlags_LockThisFrame | ImGuiInputFlags_LockUntilRelease)))); // Can only use _Any with _LockXXX flags (to eat a key away without an ID to retrieve it)
10405
1
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetKeyOwner) == 0); // Passing flags not supported by this function!
10406
    //IMGUI_DEBUG_LOG("SetKeyOwner(%s, owner_id=0x%08X, flags=%08X)\n", GetKeyName(key), owner_id, flags);
10407
10408
1
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
10409
1
    owner_data->OwnerCurr = owner_data->OwnerNext = owner_id;
10410
10411
    // We cannot lock by default as it would likely break lots of legacy code.
10412
    // In the case of using LockUntilRelease while key is not down we still lock during the frame (no key_data->Down test)
10413
1
    owner_data->LockUntilRelease = (flags & ImGuiInputFlags_LockUntilRelease) != 0;
10414
1
    owner_data->LockThisFrame = (flags & ImGuiInputFlags_LockThisFrame) != 0 || (owner_data->LockUntilRelease);
10415
1
}
10416
10417
// Rarely used helper
10418
void ImGui::SetKeyOwnersForKeyChord(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
10419
0
{
10420
0
    if (key_chord & ImGuiMod_Ctrl)      { SetKeyOwner(ImGuiMod_Ctrl, owner_id, flags); }
10421
0
    if (key_chord & ImGuiMod_Shift)     { SetKeyOwner(ImGuiMod_Shift, owner_id, flags); }
10422
0
    if (key_chord & ImGuiMod_Alt)       { SetKeyOwner(ImGuiMod_Alt, owner_id, flags); }
10423
0
    if (key_chord & ImGuiMod_Super)     { SetKeyOwner(ImGuiMod_Super, owner_id, flags); }
10424
0
    if (key_chord & ~ImGuiMod_Mask_)    { SetKeyOwner((ImGuiKey)(key_chord & ~ImGuiMod_Mask_), owner_id, flags); }
10425
0
}
10426
10427
// This is more or less equivalent to:
10428
//   if (IsItemHovered() || IsItemActive())
10429
//       SetKeyOwner(key, GetItemID());
10430
// Extensive uses of that (e.g. many calls for a single item) may want to manually perform the tests once and then call SetKeyOwner() multiple times.
10431
// More advanced usage scenarios may want to call SetKeyOwner() manually based on different condition.
10432
// Worth noting is that only one item can be hovered and only one item can be active, therefore this usage pattern doesn't need to bother with routing and priority.
10433
void ImGui::SetItemKeyOwner(ImGuiKey key, ImGuiInputFlags flags)
10434
0
{
10435
0
    ImGuiContext& g = *GImGui;
10436
0
    ImGuiID id = g.LastItemData.ID;
10437
0
    if (id == 0 || (g.HoveredId != id && g.ActiveId != id))
10438
0
        return;
10439
0
    if ((flags & ImGuiInputFlags_CondMask_) == 0)
10440
0
        flags |= ImGuiInputFlags_CondDefault_;
10441
0
    if ((g.HoveredId == id && (flags & ImGuiInputFlags_CondHovered)) || (g.ActiveId == id && (flags & ImGuiInputFlags_CondActive)))
10442
0
    {
10443
0
        IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetItemKeyOwner) == 0); // Passing flags not supported by this function!
10444
0
        SetKeyOwner(key, id, flags & ~ImGuiInputFlags_CondMask_);
10445
0
    }
10446
0
}
10447
10448
void ImGui::SetItemKeyOwner(ImGuiKey key)
10449
0
{
10450
0
    SetItemKeyOwner(key, ImGuiInputFlags_None);
10451
0
}
10452
10453
// This is the only public API until we expose owner_id versions of the API as replacements.
10454
bool ImGui::IsKeyChordPressed(ImGuiKeyChord key_chord)
10455
0
{
10456
0
    return IsKeyChordPressed(key_chord, ImGuiInputFlags_None, ImGuiKeyOwner_Any);
10457
0
}
10458
10459
// This is equivalent to comparing KeyMods + doing a IsKeyPressed()
10460
bool ImGui::IsKeyChordPressed(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id)
10461
169k
{
10462
169k
    ImGuiContext& g = *GImGui;
10463
169k
    key_chord = FixupKeyChord(key_chord);
10464
169k
    ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
10465
169k
    if (g.IO.KeyMods != mods)
10466
169k
        return false;
10467
10468
    // Special storage location for mods
10469
0
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
10470
0
    if (key == ImGuiKey_None)
10471
0
        key = ConvertSingleModFlagToKey(mods);
10472
0
    if (!IsKeyPressed(key, (flags & ImGuiInputFlags_RepeatMask_), owner_id))
10473
0
        return false;
10474
0
    return true;
10475
0
}
10476
10477
void ImGui::SetNextItemShortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags)
10478
0
{
10479
0
    ImGuiContext& g = *GImGui;
10480
0
    g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasShortcut;
10481
0
    g.NextItemData.Shortcut = key_chord;
10482
0
    g.NextItemData.ShortcutFlags = flags;
10483
0
}
10484
10485
// Called from within ItemAdd: at this point we can read from NextItemData and write to LastItemData
10486
void ImGui::ItemHandleShortcut(ImGuiID id)
10487
0
{
10488
0
    ImGuiContext& g = *GImGui;
10489
0
    ImGuiInputFlags flags = g.NextItemData.ShortcutFlags;
10490
0
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetNextItemShortcut) == 0); // Passing flags not supported by SetNextItemShortcut()!
10491
10492
0
    if (g.LastItemData.InFlags & ImGuiItemFlags_Disabled)
10493
0
        return;
10494
0
    if (flags & ImGuiInputFlags_Tooltip)
10495
0
    {
10496
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasShortcut;
10497
0
        g.LastItemData.Shortcut = g.NextItemData.Shortcut;
10498
0
    }
10499
0
    if (!Shortcut(g.NextItemData.Shortcut, flags & ImGuiInputFlags_SupportedByShortcut, id) || g.NavActivateId != 0)
10500
0
        return;
10501
10502
    // FIXME: Generalize Activation queue?
10503
0
    g.NavActivateId = id; // Will effectively disable clipping.
10504
0
    g.NavActivateFlags = ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_FromShortcut;
10505
    //if (g.ActiveId == 0 || g.ActiveId == id)
10506
0
    g.NavActivateDownId = g.NavActivatePressedId = id;
10507
0
    NavHighlightActivated(id);
10508
0
}
10509
10510
bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags)
10511
0
{
10512
0
    return Shortcut(key_chord, flags, ImGuiKeyOwner_Any);
10513
0
}
10514
10515
bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id)
10516
169k
{
10517
169k
    ImGuiContext& g = *GImGui;
10518
    //IMGUI_DEBUG_LOG("Shortcut(%s, flags=%X, owner_id=0x%08X)\n", GetKeyChordName(key_chord, g.TempBuffer.Data, g.TempBuffer.Size), flags, owner_id);
10519
10520
    // When using (owner_id == 0/Any): SetShortcutRouting() will use CurrentFocusScopeId and filter with this, so IsKeyPressed() is fine with he 0/Any.
10521
169k
    if ((flags & ImGuiInputFlags_RouteTypeMask_) == 0)
10522
0
        flags |= ImGuiInputFlags_RouteFocused;
10523
10524
    // Using 'owner_id == ImGuiKeyOwner_Any/0': auto-assign an owner based on current focus scope (each window has its focus scope by default)
10525
    // Effectively makes Shortcut() always input-owner aware.
10526
169k
    if (owner_id == ImGuiKeyOwner_Any || owner_id == ImGuiKeyOwner_NoOwner)
10527
0
        owner_id = GetRoutingIdFromOwnerId(owner_id);
10528
10529
169k
    if (g.CurrentItemFlags & ImGuiItemFlags_Disabled)
10530
0
        return false;
10531
10532
    // Submit route
10533
169k
    if (!SetShortcutRouting(key_chord, flags, owner_id))
10534
0
        return false;
10535
10536
    // Default repeat behavior for Shortcut()
10537
    // So e.g. pressing Ctrl+W and releasing Ctrl while holding W will not trigger the W shortcut.
10538
169k
    if ((flags & ImGuiInputFlags_Repeat) != 0 && (flags & ImGuiInputFlags_RepeatUntilMask_) == 0)
10539
169k
        flags |= ImGuiInputFlags_RepeatUntilKeyModsChange;
10540
10541
169k
    if (!IsKeyChordPressed(key_chord, flags, owner_id))
10542
169k
        return false;
10543
10544
    // Claim mods during the press
10545
0
    SetKeyOwnersForKeyChord(key_chord & ImGuiMod_Mask_, owner_id);
10546
10547
0
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByShortcut) == 0); // Passing flags not supported by this function!
10548
0
    return true;
10549
169k
}
10550
10551
10552
//-----------------------------------------------------------------------------
10553
// [SECTION] ERROR CHECKING
10554
//-----------------------------------------------------------------------------
10555
10556
// Verify ABI compatibility between caller code and compiled version of Dear ImGui. This helps detects some build issues.
10557
// Called by IMGUI_CHECKVERSION().
10558
// Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit
10559
// If this triggers you have mismatched headers and compiled code versions.
10560
// - It could be because of a build issue (using new headers with old compiled code)
10561
// - It could be because of mismatched configuration #define, compilation settings, packing pragma etc.
10562
//   THE CONFIGURATION SETTINGS MENTIONED IN imconfig.h MUST BE SET FOR ALL COMPILATION UNITS INVOLVED WITH DEAR IMGUI.
10563
//   Which is why it is required you put them in your imconfig file (and NOT only before including imgui.h).
10564
//   Otherwise it is possible that different compilation units would see different structure layout.
10565
//   If you don't want to modify imconfig.h you can use the IMGUI_USER_CONFIG define to change filename.
10566
bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_vert, size_t sz_idx)
10567
1
{
10568
1
    bool error = false;
10569
1
    if (strcmp(version, IMGUI_VERSION) != 0) { error = true; IM_ASSERT(strcmp(version, IMGUI_VERSION) == 0 && "Mismatched version string!"); }
10570
1
    if (sz_io    != sizeof(ImGuiIO))    { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); }
10571
1
    if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); }
10572
1
    if (sz_vec2  != sizeof(ImVec2))     { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); }
10573
1
    if (sz_vec4  != sizeof(ImVec4))     { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); }
10574
1
    if (sz_vert  != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); }
10575
1
    if (sz_idx   != sizeof(ImDrawIdx))  { error = true; IM_ASSERT(sz_idx == sizeof(ImDrawIdx) && "Mismatched struct layout!"); }
10576
1
    return !error;
10577
1
}
10578
10579
// Until 1.89 (IMGUI_VERSION_NUM < 18814) it was legal to use SetCursorPos() to extend the boundary of a parent (e.g. window or table cell)
10580
// This is causing issues and ambiguity and we need to retire that.
10581
// See https://github.com/ocornut/imgui/issues/5548 for more details.
10582
// [Scenario 1]
10583
//  Previously this would make the window content size ~200x200:
10584
//    Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();  // NOT OK
10585
//  Instead, please submit an item:
10586
//    Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End(); // OK
10587
//  Alternative:
10588
//    Begin(...) + Dummy(ImVec2(200,200)) + End(); // OK
10589
// [Scenario 2]
10590
//  For reference this is one of the issue what we aim to fix with this change:
10591
//    BeginGroup() + SomeItem("foobar") + SetCursorScreenPos(GetCursorScreenPos()) + EndGroup()
10592
//  The previous logic made SetCursorScreenPos(GetCursorScreenPos()) have a side-effect! It would erroneously incorporate ItemSpacing.y after the item into content size, making the group taller!
10593
//  While this code is a little twisted, no-one would expect SetXXX(GetXXX()) to have a side-effect. Using vertical alignment patterns could trigger this issue.
10594
void ImGui::ErrorCheckUsingSetCursorPosToExtendParentBoundaries()
10595
0
{
10596
0
    ImGuiContext& g = *GImGui;
10597
0
    ImGuiWindow* window = g.CurrentWindow;
10598
0
    IM_ASSERT(window->DC.IsSetPos);
10599
0
    window->DC.IsSetPos = false;
10600
0
#ifdef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
10601
0
    if (window->DC.CursorPos.x <= window->DC.CursorMaxPos.x && window->DC.CursorPos.y <= window->DC.CursorMaxPos.y)
10602
0
        return;
10603
0
    if (window->SkipItems)
10604
0
        return;
10605
0
    IM_ASSERT(0 && "Code uses SetCursorPos()/SetCursorScreenPos() to extend window/parent boundaries. Please submit an item e.g. Dummy() to validate extent.");
10606
#else
10607
    window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
10608
#endif
10609
0
}
10610
10611
static void ImGui::ErrorCheckNewFrameSanityChecks()
10612
84.9k
{
10613
84.9k
    ImGuiContext& g = *GImGui;
10614
10615
    // Check user IM_ASSERT macro
10616
    // (IF YOU GET A WARNING OR COMPILE ERROR HERE: it means your assert macro is incorrectly defined!
10617
    //  If your macro uses multiple statements, it NEEDS to be surrounded by a 'do { ... } while (0)' block.
10618
    //  This is a common C/C++ idiom to allow multiple statements macros to be used in control flow blocks.)
10619
    // #define IM_ASSERT(EXPR)   if (SomeCode(EXPR)) SomeMoreCode();                    // Wrong!
10620
    // #define IM_ASSERT(EXPR)   do { if (SomeCode(EXPR)) SomeMoreCode(); } while (0)   // Correct!
10621
84.9k
    if (true) IM_ASSERT(1); else IM_ASSERT(0);
10622
10623
    // Emscripten backends are often imprecise in their submission of DeltaTime. (#6114, #3644)
10624
    // Ideally the Emscripten app/backend should aim to fix or smooth this value and avoid feeding zero, but we tolerate it.
10625
#ifdef __EMSCRIPTEN__
10626
    if (g.IO.DeltaTime <= 0.0f && g.FrameCount > 0)
10627
        g.IO.DeltaTime = 0.00001f;
10628
#endif
10629
10630
    // Check user data
10631
    // (We pass an error message in the assert expression to make it visible to programmers who are not using a debugger, as most assert handlers display their argument)
10632
84.9k
    IM_ASSERT(g.Initialized);
10633
84.9k
    IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0)              && "Need a positive DeltaTime!");
10634
84.9k
    IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount)  && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
10635
84.9k
    IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f  && "Invalid DisplaySize value!");
10636
84.9k
    IM_ASSERT(g.IO.Fonts->IsBuilt()                                     && "Font Atlas not built! Make sure you called ImGui_ImplXXXX_NewFrame() function for renderer backend, which should call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8()");
10637
84.9k
    IM_ASSERT(g.Style.CurveTessellationTol > 0.0f                       && "Invalid style setting!");
10638
84.9k
    IM_ASSERT(g.Style.CircleTessellationMaxError > 0.0f                 && "Invalid style setting!");
10639
84.9k
    IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f            && "Invalid style setting!"); // Allows us to avoid a few clamps in color computations
10640
84.9k
    IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting.");
10641
84.9k
    IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right);
10642
84.9k
    IM_ASSERT(g.Style.ColorButtonPosition == ImGuiDir_Left || g.Style.ColorButtonPosition == ImGuiDir_Right);
10643
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
10644
    for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_COUNT; n++)
10645
        IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < ImGuiKey_LegacyNativeKey_END && "io.KeyMap[] contains an out of bound value (need to be 0..511, or -1 for unmapped key)");
10646
10647
    // Check: required key mapping (we intentionally do NOT check all keys to not pressure user into setting up everything, but Space is required and was only added in 1.60 WIP)
10648
    if ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && g.IO.BackendUsingLegacyKeyArrays == 1)
10649
        IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation.");
10650
#endif
10651
10652
    // Perform simple check: error if Docking or Viewport are enabled _exactly_ on frame 1 (instead of frame 0 or later), which is a common error leading to loss of .ini data.
10653
84.9k
    if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_DockingEnable) == 0)
10654
84.9k
        IM_ASSERT(0 && "Please set DockingEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
10655
84.9k
    if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable) == 0)
10656
84.9k
        IM_ASSERT(0 && "Please set ViewportsEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
10657
10658
    // Perform simple checks: multi-viewport and platform windows support
10659
84.9k
    if (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
10660
1
    {
10661
1
        if ((g.IO.BackendFlags & ImGuiBackendFlags_PlatformHasViewports) && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasViewports))
10662
0
        {
10663
0
            IM_ASSERT((g.FrameCount == 0 || g.FrameCount == g.FrameCountPlatformEnded) && "Forgot to call UpdatePlatformWindows() in main loop after EndFrame()? Check examples/ applications for reference.");
10664
0
            IM_ASSERT(g.PlatformIO.Platform_CreateWindow  != NULL && "Platform init didn't install handlers?");
10665
0
            IM_ASSERT(g.PlatformIO.Platform_DestroyWindow != NULL && "Platform init didn't install handlers?");
10666
0
            IM_ASSERT(g.PlatformIO.Platform_GetWindowPos  != NULL && "Platform init didn't install handlers?");
10667
0
            IM_ASSERT(g.PlatformIO.Platform_SetWindowPos  != NULL && "Platform init didn't install handlers?");
10668
0
            IM_ASSERT(g.PlatformIO.Platform_GetWindowSize != NULL && "Platform init didn't install handlers?");
10669
0
            IM_ASSERT(g.PlatformIO.Platform_SetWindowSize != NULL && "Platform init didn't install handlers?");
10670
0
            IM_ASSERT(g.PlatformIO.Monitors.Size > 0 && "Platform init didn't setup Monitors list?");
10671
0
            IM_ASSERT((g.Viewports[0]->PlatformUserData != NULL || g.Viewports[0]->PlatformHandle != NULL) && "Platform init didn't setup main viewport.");
10672
0
            if (g.IO.ConfigDockingTransparentPayload && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
10673
0
                IM_ASSERT(g.PlatformIO.Platform_SetWindowAlpha != NULL && "Platform_SetWindowAlpha handler is required to use io.ConfigDockingTransparent!");
10674
0
        }
10675
1
        else
10676
1
        {
10677
            // Disable feature, our backends do not support it
10678
1
            g.IO.ConfigFlags &= ~ImGuiConfigFlags_ViewportsEnable;
10679
1
        }
10680
10681
        // Perform simple checks on platform monitor data + compute a total bounding box for quick early outs
10682
1
        for (ImGuiPlatformMonitor& mon : g.PlatformIO.Monitors)
10683
0
        {
10684
0
            IM_UNUSED(mon);
10685
0
            IM_ASSERT(mon.MainSize.x > 0.0f && mon.MainSize.y > 0.0f && "Monitor main bounds not setup properly.");
10686
0
            IM_ASSERT(ImRect(mon.MainPos, mon.MainPos + mon.MainSize).Contains(ImRect(mon.WorkPos, mon.WorkPos + mon.WorkSize)) && "Monitor work bounds not setup properly. If you don't have work area information, just copy MainPos/MainSize into them.");
10687
0
            IM_ASSERT(mon.DpiScale != 0.0f);
10688
0
        }
10689
1
    }
10690
84.9k
}
10691
10692
static void ImGui::ErrorCheckEndFrameSanityChecks()
10693
84.9k
{
10694
84.9k
    ImGuiContext& g = *GImGui;
10695
10696
    // Verify that io.KeyXXX fields haven't been tampered with. Key mods should not be modified between NewFrame() and EndFrame()
10697
    // One possible reason leading to this assert is that your backends update inputs _AFTER_ NewFrame().
10698
    // It is known that when some modal native windows called mid-frame takes focus away, some backends such as GLFW will
10699
    // send key release events mid-frame. This would normally trigger this assertion and lead to sheared inputs.
10700
    // We silently accommodate for this case by ignoring the case where all io.KeyXXX modifiers were released (aka key_mod_flags == 0),
10701
    // while still correctly asserting on mid-frame key press events.
10702
84.9k
    const ImGuiKeyChord key_mods = GetMergedModsFromKeys();
10703
84.9k
    IM_ASSERT((key_mods == 0 || g.IO.KeyMods == key_mods) && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods");
10704
84.9k
    IM_UNUSED(key_mods);
10705
10706
    // [EXPERIMENTAL] Recover from errors: You may call this yourself before EndFrame().
10707
    //ErrorCheckEndFrameRecover();
10708
10709
    // Report when there is a mismatch of Begin/BeginChild vs End/EndChild calls. Important: Remember that the Begin/BeginChild API requires you
10710
    // to always call End/EndChild even if Begin/BeginChild returns false! (this is unfortunately inconsistent with most other Begin* API).
10711
84.9k
    if (g.CurrentWindowStack.Size != 1)
10712
0
    {
10713
0
        if (g.CurrentWindowStack.Size > 1)
10714
0
        {
10715
0
            ImGuiWindow* window = g.CurrentWindowStack.back().Window; // <-- This window was not Ended!
10716
0
            IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you forget to call End/EndChild?");
10717
0
            IM_UNUSED(window);
10718
0
            while (g.CurrentWindowStack.Size > 1)
10719
0
                End();
10720
0
        }
10721
0
        else
10722
0
        {
10723
0
            IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you call End/EndChild too much?");
10724
0
        }
10725
0
    }
10726
10727
84.9k
    IM_ASSERT_USER_ERROR(g.GroupStack.Size == 0, "Missing EndGroup call!");
10728
84.9k
}
10729
10730
// Experimental recovery from incorrect usage of BeginXXX/EndXXX/PushXXX/PopXXX calls.
10731
// Must be called during or before EndFrame().
10732
// This is generally flawed as we are not necessarily End/Popping things in the right order.
10733
// FIXME: Can't recover from inside BeginTabItem/EndTabItem yet.
10734
// FIXME: Can't recover from interleaved BeginTabBar/Begin
10735
void    ImGui::ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, void* user_data)
10736
0
{
10737
    // PVS-Studio V1044 is "Loop break conditions do not depend on the number of iterations"
10738
0
    ImGuiContext& g = *GImGui;
10739
0
    while (g.CurrentWindowStack.Size > 0) //-V1044
10740
0
    {
10741
0
        ErrorCheckEndWindowRecover(log_callback, user_data);
10742
0
        ImGuiWindow* window = g.CurrentWindow;
10743
0
        if (g.CurrentWindowStack.Size == 1)
10744
0
        {
10745
0
            IM_ASSERT(window->IsFallbackWindow);
10746
0
            break;
10747
0
        }
10748
0
        if (window->Flags & ImGuiWindowFlags_ChildWindow)
10749
0
        {
10750
0
            if (log_callback) log_callback(user_data, "Recovered from missing EndChild() for '%s'", window->Name);
10751
0
            EndChild();
10752
0
        }
10753
0
        else
10754
0
        {
10755
0
            if (log_callback) log_callback(user_data, "Recovered from missing End() for '%s'", window->Name);
10756
0
            End();
10757
0
        }
10758
0
    }
10759
0
}
10760
10761
// Must be called before End()/EndChild()
10762
void    ImGui::ErrorCheckEndWindowRecover(ImGuiErrorLogCallback log_callback, void* user_data)
10763
0
{
10764
0
    ImGuiContext& g = *GImGui;
10765
0
    while (g.CurrentTable && (g.CurrentTable->OuterWindow == g.CurrentWindow || g.CurrentTable->InnerWindow == g.CurrentWindow))
10766
0
    {
10767
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndTable() in '%s'", g.CurrentTable->OuterWindow->Name);
10768
0
        EndTable();
10769
0
    }
10770
10771
0
    ImGuiWindow* window = g.CurrentWindow;
10772
0
    ImGuiStackSizes* stack_sizes = &g.CurrentWindowStack.back().StackSizesOnBegin;
10773
0
    IM_ASSERT(window != NULL);
10774
0
    while (g.CurrentTabBar != NULL) //-V1044
10775
0
    {
10776
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndTabBar() in '%s'", window->Name);
10777
0
        EndTabBar();
10778
0
    }
10779
0
    while (g.CurrentMultiSelect != NULL && g.CurrentMultiSelect->Storage->Window == window)
10780
0
    {
10781
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndMultiSelect() in '%s'", window->Name);
10782
0
        EndMultiSelect();
10783
0
    }
10784
0
    while (window->DC.TreeDepth > 0)
10785
0
    {
10786
0
        if (log_callback) log_callback(user_data, "Recovered from missing TreePop() in '%s'", window->Name);
10787
0
        TreePop();
10788
0
    }
10789
0
    while (g.GroupStack.Size > stack_sizes->SizeOfGroupStack) //-V1044
10790
0
    {
10791
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndGroup() in '%s'", window->Name);
10792
0
        EndGroup();
10793
0
    }
10794
0
    while (window->IDStack.Size > 1)
10795
0
    {
10796
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopID() in '%s'", window->Name);
10797
0
        PopID();
10798
0
    }
10799
0
    while (g.DisabledStackSize > stack_sizes->SizeOfDisabledStack) //-V1044
10800
0
    {
10801
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndDisabled() in '%s'", window->Name);
10802
0
        if (g.CurrentItemFlags & ImGuiItemFlags_Disabled)
10803
0
            EndDisabled();
10804
0
        else
10805
0
        {
10806
0
            EndDisabledOverrideReenable();
10807
0
            g.CurrentWindowStack.back().DisabledOverrideReenable = false;
10808
0
        }
10809
0
    }
10810
0
    while (g.ColorStack.Size > stack_sizes->SizeOfColorStack)
10811
0
    {
10812
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopStyleColor() in '%s' for ImGuiCol_%s", window->Name, GetStyleColorName(g.ColorStack.back().Col));
10813
0
        PopStyleColor();
10814
0
    }
10815
0
    while (g.ItemFlagsStack.Size > stack_sizes->SizeOfItemFlagsStack) //-V1044
10816
0
    {
10817
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopItemFlag() in '%s'", window->Name);
10818
0
        PopItemFlag();
10819
0
    }
10820
0
    while (g.StyleVarStack.Size > stack_sizes->SizeOfStyleVarStack) //-V1044
10821
0
    {
10822
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopStyleVar() in '%s'", window->Name);
10823
0
        PopStyleVar();
10824
0
    }
10825
0
    while (g.FontStack.Size > stack_sizes->SizeOfFontStack) //-V1044
10826
0
    {
10827
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopFont() in '%s'", window->Name);
10828
0
        PopFont();
10829
0
    }
10830
0
    while (g.FocusScopeStack.Size > stack_sizes->SizeOfFocusScopeStack + 1) //-V1044
10831
0
    {
10832
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopFocusScope() in '%s'", window->Name);
10833
0
        PopFocusScope();
10834
0
    }
10835
0
}
10836
10837
// Save current stack sizes for later compare
10838
void ImGuiStackSizes::SetToContextState(ImGuiContext* ctx)
10839
193k
{
10840
193k
    ImGuiContext& g = *ctx;
10841
193k
    ImGuiWindow* window = g.CurrentWindow;
10842
193k
    SizeOfIDStack = (short)window->IDStack.Size;
10843
193k
    SizeOfColorStack = (short)g.ColorStack.Size;
10844
193k
    SizeOfStyleVarStack = (short)g.StyleVarStack.Size;
10845
193k
    SizeOfFontStack = (short)g.FontStack.Size;
10846
193k
    SizeOfFocusScopeStack = (short)g.FocusScopeStack.Size;
10847
193k
    SizeOfGroupStack = (short)g.GroupStack.Size;
10848
193k
    SizeOfItemFlagsStack = (short)g.ItemFlagsStack.Size;
10849
193k
    SizeOfBeginPopupStack = (short)g.BeginPopupStack.Size;
10850
193k
    SizeOfDisabledStack = (short)g.DisabledStackSize;
10851
193k
}
10852
10853
// Compare to detect usage errors
10854
void ImGuiStackSizes::CompareWithContextState(ImGuiContext* ctx)
10855
193k
{
10856
193k
    ImGuiContext& g = *ctx;
10857
193k
    ImGuiWindow* window = g.CurrentWindow;
10858
193k
    IM_UNUSED(window);
10859
10860
    // Window stacks
10861
    // NOT checking: DC.ItemWidth, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin)
10862
193k
    IM_ASSERT(SizeOfIDStack         == window->IDStack.Size     && "PushID/PopID or TreeNode/TreePop Mismatch!");
10863
10864
    // Global stacks
10865
    // For color, style and font stacks there is an incentive to use Push/Begin/Pop/.../End patterns, so we relax our checks a little to allow them.
10866
193k
    IM_ASSERT(SizeOfGroupStack      == g.GroupStack.Size        && "BeginGroup/EndGroup Mismatch!");
10867
193k
    IM_ASSERT(SizeOfBeginPopupStack == g.BeginPopupStack.Size   && "BeginPopup/EndPopup or BeginMenu/EndMenu Mismatch!");
10868
193k
    IM_ASSERT(SizeOfDisabledStack   == g.DisabledStackSize      && "BeginDisabled/EndDisabled Mismatch!");
10869
193k
    IM_ASSERT(SizeOfItemFlagsStack  >= g.ItemFlagsStack.Size    && "PushItemFlag/PopItemFlag Mismatch!");
10870
193k
    IM_ASSERT(SizeOfColorStack      >= g.ColorStack.Size        && "PushStyleColor/PopStyleColor Mismatch!");
10871
193k
    IM_ASSERT(SizeOfStyleVarStack   >= g.StyleVarStack.Size     && "PushStyleVar/PopStyleVar Mismatch!");
10872
193k
    IM_ASSERT(SizeOfFontStack       >= g.FontStack.Size         && "PushFont/PopFont Mismatch!");
10873
193k
    IM_ASSERT(SizeOfFocusScopeStack == g.FocusScopeStack.Size   && "PushFocusScope/PopFocusScope Mismatch!");
10874
193k
}
10875
10876
//-----------------------------------------------------------------------------
10877
// [SECTION] ITEM SUBMISSION
10878
//-----------------------------------------------------------------------------
10879
// - KeepAliveID()
10880
// - ItemAdd()
10881
//-----------------------------------------------------------------------------
10882
10883
// Code not using ItemAdd() may need to call this manually otherwise ActiveId will be cleared. In IMGUI_VERSION_NUM < 18717 this was called by GetID().
10884
void ImGui::KeepAliveID(ImGuiID id)
10885
350k
{
10886
350k
    ImGuiContext& g = *GImGui;
10887
350k
    if (g.ActiveId == id)
10888
1
        g.ActiveIdIsAlive = id;
10889
350k
    if (g.ActiveIdPreviousFrame == id)
10890
1
        g.ActiveIdPreviousFrameIsAlive = true;
10891
350k
}
10892
10893
// Declare item bounding box for clipping and interaction.
10894
// Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
10895
// declare their minimum size requirement to ItemSize() and provide a larger region to ItemAdd() which is used drawing/interaction.
10896
// THIS IS IN THE PERFORMANCE CRITICAL PATH (UNTIL THE CLIPPING TEST AND EARLY-RETURN)
10897
IM_MSVC_RUNTIME_CHECKS_OFF
10898
bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg, ImGuiItemFlags extra_flags)
10899
373k
{
10900
373k
    ImGuiContext& g = *GImGui;
10901
373k
    ImGuiWindow* window = g.CurrentWindow;
10902
10903
    // Set item data
10904
    // (DisplayRect is left untouched, made valid when ImGuiItemStatusFlags_HasDisplayRect is set)
10905
373k
    g.LastItemData.ID = id;
10906
373k
    g.LastItemData.Rect = bb;
10907
373k
    g.LastItemData.NavRect = nav_bb_arg ? *nav_bb_arg : bb;
10908
373k
    g.LastItemData.InFlags = g.CurrentItemFlags | g.NextItemData.ItemFlags | extra_flags;
10909
373k
    g.LastItemData.StatusFlags = ImGuiItemStatusFlags_None;
10910
    // Note: we don't copy 'g.NextItemData.SelectionUserData' to an hypothetical g.LastItemData.SelectionUserData: since the former is not cleared.
10911
10912
373k
    if (id != 0)
10913
350k
    {
10914
350k
        KeepAliveID(id);
10915
10916
        // Directional navigation processing
10917
        // Runs prior to clipping early-out
10918
        //  (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget
10919
        //  (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests
10920
        //      unfortunately, but it is still limited to one window. It may not scale very well for windows with ten of
10921
        //      thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame.
10922
        //      We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able
10923
        //      to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick).
10924
        // We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null.
10925
        // If we crash on a NULL g.NavWindow we need to fix the bug elsewhere.
10926
350k
        if (!(g.LastItemData.InFlags & ImGuiItemFlags_NoNav))
10927
189k
        {
10928
            // FIMXE-NAV: investigate changing the window tests into a simple 'if (g.NavFocusScopeId == g.CurrentFocusScopeId)' test.
10929
189k
            window->DC.NavLayersActiveMaskNext |= (1 << window->DC.NavLayerCurrent);
10930
189k
            if (g.NavId == id || g.NavAnyRequest)
10931
5.26k
                if (g.NavWindow->RootWindowForNav == window->RootWindowForNav)
10932
2.25k
                    if (window == g.NavWindow || ((window->ChildFlags | g.NavWindow->ChildFlags) & ImGuiChildFlags_NavFlattened))
10933
2.25k
                        NavProcessItem();
10934
189k
        }
10935
10936
350k
        if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasShortcut)
10937
0
            ItemHandleShortcut(id);
10938
350k
    }
10939
10940
    // Lightweight clear of SetNextItemXXX data.
10941
373k
    g.NextItemData.Flags = ImGuiNextItemDataFlags_None;
10942
373k
    g.NextItemData.ItemFlags = ImGuiItemFlags_None;
10943
10944
#ifdef IMGUI_ENABLE_TEST_ENGINE
10945
    if (id != 0)
10946
        IMGUI_TEST_ENGINE_ITEM_ADD(id, g.LastItemData.NavRect, &g.LastItemData);
10947
#endif
10948
10949
    // Clipping test
10950
    // (this is an inline copy of IsClippedEx() so we can reuse the is_rect_visible value, otherwise we'd do 'if (IsClippedEx(bb, id)) return false')
10951
    // g.NavActivateId is not necessarily == g.NavId, in the case of remote activation (e.g. shortcuts)
10952
373k
    const bool is_rect_visible = bb.Overlaps(window->ClipRect);
10953
373k
    if (!is_rect_visible)
10954
119k
        if (id == 0 || (id != g.ActiveId && id != g.ActiveIdPreviousFrame && id != g.NavId && id != g.NavActivateId))
10955
119k
            if (!g.ItemUnclipByLog)
10956
119k
                return false;
10957
10958
    // [DEBUG]
10959
254k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
10960
254k
    if (id != 0)
10961
251k
    {
10962
251k
        if (id == g.DebugLocateId)
10963
0
            DebugLocateItemResolveWithLastItem();
10964
10965
        // [DEBUG] People keep stumbling on this problem and using "" as identifier in the root of a window instead of "##something".
10966
        // Empty identifier are valid and useful in a small amount of cases, but 99.9% of the time you want to use "##something".
10967
        // READ THE FAQ: https://dearimgui.com/faq
10968
251k
        IM_ASSERT(id != window->ID && "Cannot have an empty ID at the root of a window. If you need an empty label, use ## and read the FAQ about how the ID Stack works!");
10969
251k
    }
10970
    //if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
10971
    //if ((g.LastItemData.InFlags & ImGuiItemFlags_NoNav) == 0)
10972
    //    window->DrawList->AddRect(g.LastItemData.NavRect.Min, g.LastItemData.NavRect.Max, IM_COL32(255,255,0,255)); // [DEBUG]
10973
254k
#endif
10974
10975
    // We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)
10976
254k
    if (is_rect_visible)
10977
254k
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Visible;
10978
254k
    if (IsMouseHoveringRect(bb.Min, bb.Max))
10979
3.86k
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredRect;
10980
254k
    return true;
10981
373k
}
10982
IM_MSVC_RUNTIME_CHECKS_RESTORE
10983
10984
//-----------------------------------------------------------------------------
10985
// [SECTION] LAYOUT
10986
//-----------------------------------------------------------------------------
10987
// - ItemSize()
10988
// - SameLine()
10989
// - GetCursorScreenPos()
10990
// - SetCursorScreenPos()
10991
// - GetCursorPos(), GetCursorPosX(), GetCursorPosY()
10992
// - SetCursorPos(), SetCursorPosX(), SetCursorPosY()
10993
// - GetCursorStartPos()
10994
// - Indent()
10995
// - Unindent()
10996
// - SetNextItemWidth()
10997
// - PushItemWidth()
10998
// - PushMultiItemsWidths()
10999
// - PopItemWidth()
11000
// - CalcItemWidth()
11001
// - CalcItemSize()
11002
// - GetTextLineHeight()
11003
// - GetTextLineHeightWithSpacing()
11004
// - GetFrameHeight()
11005
// - GetFrameHeightWithSpacing()
11006
// - GetContentRegionMax()
11007
// - GetContentRegionAvail(),
11008
// - BeginGroup()
11009
// - EndGroup()
11010
// Also see in imgui_widgets: tab bars, and in imgui_tables: tables, columns.
11011
//-----------------------------------------------------------------------------
11012
11013
// Advance cursor given item size for layout.
11014
// Register minimum needed size so it can extend the bounding box used for auto-fit calculation.
11015
// See comments in ItemAdd() about how/why the size provided to ItemSize() vs ItemAdd() may often different.
11016
// THIS IS IN THE PERFORMANCE CRITICAL PATH.
11017
IM_MSVC_RUNTIME_CHECKS_OFF
11018
void ImGui::ItemSize(const ImVec2& size, float text_baseline_y)
11019
47.4k
{
11020
47.4k
    ImGuiContext& g = *GImGui;
11021
47.4k
    ImGuiWindow* window = g.CurrentWindow;
11022
47.4k
    if (window->SkipItems)
11023
0
        return;
11024
11025
    // We increase the height in this function to accommodate for baseline offset.
11026
    // In theory we should be offsetting the starting position (window->DC.CursorPos), that will be the topic of a larger refactor,
11027
    // but since ItemSize() is not yet an API that moves the cursor (to handle e.g. wrapping) enlarging the height has the same effect.
11028
47.4k
    const float offset_to_match_baseline_y = (text_baseline_y >= 0) ? ImMax(0.0f, window->DC.CurrLineTextBaseOffset - text_baseline_y) : 0.0f;
11029
11030
47.4k
    const float line_y1 = window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y;
11031
47.4k
    const float line_height = ImMax(window->DC.CurrLineSize.y, /*ImMax(*/window->DC.CursorPos.y - line_y1/*, 0.0f)*/ + size.y + offset_to_match_baseline_y);
11032
11033
    // Always align ourselves on pixel boundaries
11034
    //if (g.IO.KeyAlt) window->DrawList->AddRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(size.x, line_height), IM_COL32(255,0,0,200)); // [DEBUG]
11035
47.4k
    window->DC.CursorPosPrevLine.x = window->DC.CursorPos.x + size.x;
11036
47.4k
    window->DC.CursorPosPrevLine.y = line_y1;
11037
47.4k
    window->DC.CursorPos.x = IM_TRUNC(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);    // Next line
11038
47.4k
    window->DC.CursorPos.y = IM_TRUNC(line_y1 + line_height + g.Style.ItemSpacing.y);                       // Next line
11039
47.4k
    window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x);
11040
47.4k
    window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y);
11041
    //if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]
11042
11043
47.4k
    window->DC.PrevLineSize.y = line_height;
11044
47.4k
    window->DC.CurrLineSize.y = 0.0f;
11045
47.4k
    window->DC.PrevLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, text_baseline_y);
11046
47.4k
    window->DC.CurrLineTextBaseOffset = 0.0f;
11047
47.4k
    window->DC.IsSameLine = window->DC.IsSetPos = false;
11048
11049
    // Horizontal layout mode
11050
47.4k
    if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
11051
0
        SameLine();
11052
47.4k
}
11053
IM_MSVC_RUNTIME_CHECKS_RESTORE
11054
11055
// Gets back to previous line and continue with horizontal layout
11056
//      offset_from_start_x == 0 : follow right after previous item
11057
//      offset_from_start_x != 0 : align to specified x position (relative to window/group left)
11058
//      spacing_w < 0            : use default spacing if offset_from_start_x == 0, no spacing if offset_from_start_x != 0
11059
//      spacing_w >= 0           : enforce spacing amount
11060
void ImGui::SameLine(float offset_from_start_x, float spacing_w)
11061
0
{
11062
0
    ImGuiContext& g = *GImGui;
11063
0
    ImGuiWindow* window = g.CurrentWindow;
11064
0
    if (window->SkipItems)
11065
0
        return;
11066
11067
0
    if (offset_from_start_x != 0.0f)
11068
0
    {
11069
0
        if (spacing_w < 0.0f)
11070
0
            spacing_w = 0.0f;
11071
0
        window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + offset_from_start_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x;
11072
0
        window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
11073
0
    }
11074
0
    else
11075
0
    {
11076
0
        if (spacing_w < 0.0f)
11077
0
            spacing_w = g.Style.ItemSpacing.x;
11078
0
        window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;
11079
0
        window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
11080
0
    }
11081
0
    window->DC.CurrLineSize = window->DC.PrevLineSize;
11082
0
    window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
11083
0
    window->DC.IsSameLine = true;
11084
0
}
11085
11086
ImVec2 ImGui::GetCursorScreenPos()
11087
45.7k
{
11088
45.7k
    ImGuiWindow* window = GetCurrentWindowRead();
11089
45.7k
    return window->DC.CursorPos;
11090
45.7k
}
11091
11092
void ImGui::SetCursorScreenPos(const ImVec2& pos)
11093
0
{
11094
0
    ImGuiWindow* window = GetCurrentWindow();
11095
0
    window->DC.CursorPos = pos;
11096
    //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
11097
0
    window->DC.IsSetPos = true;
11098
0
}
11099
11100
// User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient.
11101
// Conversion happens as we pass the value to user, but it makes our naming convention confusing because GetCursorPos() == (DC.CursorPos - window.Pos). May want to rename 'DC.CursorPos'.
11102
ImVec2 ImGui::GetCursorPos()
11103
0
{
11104
0
    ImGuiWindow* window = GetCurrentWindowRead();
11105
0
    return window->DC.CursorPos - window->Pos + window->Scroll;
11106
0
}
11107
11108
float ImGui::GetCursorPosX()
11109
0
{
11110
0
    ImGuiWindow* window = GetCurrentWindowRead();
11111
0
    return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x;
11112
0
}
11113
11114
float ImGui::GetCursorPosY()
11115
0
{
11116
0
    ImGuiWindow* window = GetCurrentWindowRead();
11117
0
    return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y;
11118
0
}
11119
11120
void ImGui::SetCursorPos(const ImVec2& local_pos)
11121
0
{
11122
0
    ImGuiWindow* window = GetCurrentWindow();
11123
0
    window->DC.CursorPos = window->Pos - window->Scroll + local_pos;
11124
    //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
11125
0
    window->DC.IsSetPos = true;
11126
0
}
11127
11128
void ImGui::SetCursorPosX(float x)
11129
0
{
11130
0
    ImGuiWindow* window = GetCurrentWindow();
11131
0
    window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x;
11132
    //window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x);
11133
0
    window->DC.IsSetPos = true;
11134
0
}
11135
11136
void ImGui::SetCursorPosY(float y)
11137
0
{
11138
0
    ImGuiWindow* window = GetCurrentWindow();
11139
0
    window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y;
11140
    //window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
11141
0
    window->DC.IsSetPos = true;
11142
0
}
11143
11144
ImVec2 ImGui::GetCursorStartPos()
11145
0
{
11146
0
    ImGuiWindow* window = GetCurrentWindowRead();
11147
0
    return window->DC.CursorStartPos - window->Pos;
11148
0
}
11149
11150
void ImGui::Indent(float indent_w)
11151
0
{
11152
0
    ImGuiContext& g = *GImGui;
11153
0
    ImGuiWindow* window = GetCurrentWindow();
11154
0
    window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
11155
0
    window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
11156
0
}
11157
11158
void ImGui::Unindent(float indent_w)
11159
0
{
11160
0
    ImGuiContext& g = *GImGui;
11161
0
    ImGuiWindow* window = GetCurrentWindow();
11162
0
    window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
11163
0
    window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
11164
0
}
11165
11166
// Affect large frame+labels widgets only.
11167
void ImGui::SetNextItemWidth(float item_width)
11168
0
{
11169
0
    ImGuiContext& g = *GImGui;
11170
0
    g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasWidth;
11171
0
    g.NextItemData.Width = item_width;
11172
0
}
11173
11174
// FIXME: Remove the == 0.0f behavior?
11175
void ImGui::PushItemWidth(float item_width)
11176
0
{
11177
0
    ImGuiContext& g = *GImGui;
11178
0
    ImGuiWindow* window = g.CurrentWindow;
11179
0
    window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
11180
0
    window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
11181
0
    g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
11182
0
}
11183
11184
void ImGui::PushMultiItemsWidths(int components, float w_full)
11185
0
{
11186
0
    ImGuiContext& g = *GImGui;
11187
0
    ImGuiWindow* window = g.CurrentWindow;
11188
0
    IM_ASSERT(components > 0);
11189
0
    const ImGuiStyle& style = g.Style;
11190
0
    window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
11191
0
    float w_items = w_full - style.ItemInnerSpacing.x * (components - 1);
11192
0
    float prev_split = w_items;
11193
0
    for (int i = components - 1; i > 0; i--)
11194
0
    {
11195
0
        float next_split = IM_TRUNC(w_items * i / components);
11196
0
        window->DC.ItemWidthStack.push_back(ImMax(prev_split - next_split, 1.0f));
11197
0
        prev_split = next_split;
11198
0
    }
11199
0
    window->DC.ItemWidth = ImMax(prev_split, 1.0f);
11200
0
    g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
11201
0
}
11202
11203
void ImGui::PopItemWidth()
11204
0
{
11205
0
    ImGuiWindow* window = GetCurrentWindow();
11206
0
    window->DC.ItemWidth = window->DC.ItemWidthStack.back();
11207
0
    window->DC.ItemWidthStack.pop_back();
11208
0
}
11209
11210
// Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth().
11211
// The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags()
11212
float ImGui::CalcItemWidth()
11213
0
{
11214
0
    ImGuiContext& g = *GImGui;
11215
0
    ImGuiWindow* window = g.CurrentWindow;
11216
0
    float w;
11217
0
    if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasWidth)
11218
0
        w = g.NextItemData.Width;
11219
0
    else
11220
0
        w = window->DC.ItemWidth;
11221
0
    if (w < 0.0f)
11222
0
    {
11223
0
        float region_avail_x = GetContentRegionAvail().x;
11224
0
        w = ImMax(1.0f, region_avail_x + w);
11225
0
    }
11226
0
    w = IM_TRUNC(w);
11227
0
    return w;
11228
0
}
11229
11230
// [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth().
11231
// Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical.
11232
// Note that only CalcItemWidth() is publicly exposed.
11233
// The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable)
11234
ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h)
11235
23.7k
{
11236
23.7k
    ImVec2 avail;
11237
23.7k
    if (size.x < 0.0f || size.y < 0.0f)
11238
0
        avail = GetContentRegionAvail();
11239
11240
23.7k
    if (size.x == 0.0f)
11241
3.75k
        size.x = default_w;
11242
19.9k
    else if (size.x < 0.0f)
11243
0
        size.x = ImMax(4.0f, avail.x + size.x); // <-- size.x is negative here so we are subtracting
11244
11245
23.7k
    if (size.y == 0.0f)
11246
2.47k
        size.y = default_h;
11247
21.2k
    else if (size.y < 0.0f)
11248
0
        size.y = ImMax(4.0f, avail.y + size.y); // <-- size.y is negative here so we are subtracting
11249
11250
23.7k
    return size;
11251
23.7k
}
11252
11253
float ImGui::GetTextLineHeight()
11254
0
{
11255
0
    ImGuiContext& g = *GImGui;
11256
0
    return g.FontSize;
11257
0
}
11258
11259
float ImGui::GetTextLineHeightWithSpacing()
11260
23.7k
{
11261
23.7k
    ImGuiContext& g = *GImGui;
11262
23.7k
    return g.FontSize + g.Style.ItemSpacing.y;
11263
23.7k
}
11264
11265
float ImGui::GetFrameHeight()
11266
0
{
11267
0
    ImGuiContext& g = *GImGui;
11268
0
    return g.FontSize + g.Style.FramePadding.y * 2.0f;
11269
0
}
11270
11271
float ImGui::GetFrameHeightWithSpacing()
11272
0
{
11273
0
    ImGuiContext& g = *GImGui;
11274
0
    return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
11275
0
}
11276
11277
ImVec2 ImGui::GetContentRegionAvail()
11278
23.7k
{
11279
23.7k
    ImGuiContext& g = *GImGui;
11280
23.7k
    ImGuiWindow* window = g.CurrentWindow;
11281
23.7k
    ImVec2 mx = (window->DC.CurrentColumns || g.CurrentTable) ? window->WorkRect.Max : window->ContentRegionRect.Max;
11282
23.7k
    return mx - window->DC.CursorPos;
11283
23.7k
}
11284
11285
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
11286
11287
// You should never need those functions. Always use GetCursorScreenPos() and GetContentRegionAvail()!
11288
// They are bizarre local-coordinates which don't play well with scrolling.
11289
ImVec2 ImGui::GetContentRegionMax()
11290
{
11291
    return GetContentRegionAvail() + GetCursorScreenPos() - GetWindowPos();
11292
}
11293
11294
ImVec2 ImGui::GetWindowContentRegionMin()
11295
{
11296
    ImGuiWindow* window = GImGui->CurrentWindow;
11297
    return window->ContentRegionRect.Min - window->Pos;
11298
}
11299
11300
ImVec2 ImGui::GetWindowContentRegionMax()
11301
{
11302
    ImGuiWindow* window = GImGui->CurrentWindow;
11303
    return window->ContentRegionRect.Max - window->Pos;
11304
}
11305
#endif
11306
11307
// Lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.)
11308
// Groups are currently a mishmash of functionalities which should perhaps be clarified and separated.
11309
// FIXME-OPT: Could we safely early out on ->SkipItems?
11310
void ImGui::BeginGroup()
11311
0
{
11312
0
    ImGuiContext& g = *GImGui;
11313
0
    ImGuiWindow* window = g.CurrentWindow;
11314
11315
0
    g.GroupStack.resize(g.GroupStack.Size + 1);
11316
0
    ImGuiGroupData& group_data = g.GroupStack.back();
11317
0
    group_data.WindowID = window->ID;
11318
0
    group_data.BackupCursorPos = window->DC.CursorPos;
11319
0
    group_data.BackupCursorPosPrevLine = window->DC.CursorPosPrevLine;
11320
0
    group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
11321
0
    group_data.BackupIndent = window->DC.Indent;
11322
0
    group_data.BackupGroupOffset = window->DC.GroupOffset;
11323
0
    group_data.BackupCurrLineSize = window->DC.CurrLineSize;
11324
0
    group_data.BackupCurrLineTextBaseOffset = window->DC.CurrLineTextBaseOffset;
11325
0
    group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive;
11326
0
    group_data.BackupHoveredIdIsAlive = g.HoveredId != 0;
11327
0
    group_data.BackupIsSameLine = window->DC.IsSameLine;
11328
0
    group_data.BackupActiveIdPreviousFrameIsAlive = g.ActiveIdPreviousFrameIsAlive;
11329
0
    group_data.EmitItem = true;
11330
11331
0
    window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x;
11332
0
    window->DC.Indent = window->DC.GroupOffset;
11333
0
    window->DC.CursorMaxPos = window->DC.CursorPos;
11334
0
    window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
11335
0
    if (g.LogEnabled)
11336
0
        g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
11337
0
}
11338
11339
void ImGui::EndGroup()
11340
0
{
11341
0
    ImGuiContext& g = *GImGui;
11342
0
    ImGuiWindow* window = g.CurrentWindow;
11343
0
    IM_ASSERT(g.GroupStack.Size > 0); // Mismatched BeginGroup()/EndGroup() calls
11344
11345
0
    ImGuiGroupData& group_data = g.GroupStack.back();
11346
0
    IM_ASSERT(group_data.WindowID == window->ID); // EndGroup() in wrong window?
11347
11348
0
    if (window->DC.IsSetPos)
11349
0
        ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
11350
11351
    // Include LastItemData.Rect.Max as a workaround for e.g. EndTable() undershooting with CursorMaxPos report. (#7543)
11352
0
    ImRect group_bb(group_data.BackupCursorPos, ImMax(ImMax(window->DC.CursorMaxPos, g.LastItemData.Rect.Max), group_data.BackupCursorPos));
11353
0
    window->DC.CursorPos = group_data.BackupCursorPos;
11354
0
    window->DC.CursorPosPrevLine = group_data.BackupCursorPosPrevLine;
11355
0
    window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, group_bb.Max);
11356
0
    window->DC.Indent = group_data.BackupIndent;
11357
0
    window->DC.GroupOffset = group_data.BackupGroupOffset;
11358
0
    window->DC.CurrLineSize = group_data.BackupCurrLineSize;
11359
0
    window->DC.CurrLineTextBaseOffset = group_data.BackupCurrLineTextBaseOffset;
11360
0
    window->DC.IsSameLine = group_data.BackupIsSameLine;
11361
0
    if (g.LogEnabled)
11362
0
        g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
11363
11364
0
    if (!group_data.EmitItem)
11365
0
    {
11366
0
        g.GroupStack.pop_back();
11367
0
        return;
11368
0
    }
11369
11370
0
    window->DC.CurrLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrLineTextBaseOffset); // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now.
11371
0
    ItemSize(group_bb.GetSize());
11372
0
    ItemAdd(group_bb, 0, NULL, ImGuiItemFlags_NoTabStop);
11373
11374
    // If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive(), IsItemDeactivated() etc. will be functional on the entire group.
11375
    // It would be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but would put a little more burden on individual widgets.
11376
    // Also if you grep for LastItemId you'll notice it is only used in that context.
11377
    // (The two tests not the same because ActiveIdIsAlive is an ID itself, in order to be able to handle ActiveId being overwritten during the frame.)
11378
0
    const bool group_contains_curr_active_id = (group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId;
11379
0
    const bool group_contains_prev_active_id = (group_data.BackupActiveIdPreviousFrameIsAlive == false) && (g.ActiveIdPreviousFrameIsAlive == true);
11380
0
    if (group_contains_curr_active_id)
11381
0
        g.LastItemData.ID = g.ActiveId;
11382
0
    else if (group_contains_prev_active_id)
11383
0
        g.LastItemData.ID = g.ActiveIdPreviousFrame;
11384
0
    g.LastItemData.Rect = group_bb;
11385
11386
    // Forward Hovered flag
11387
0
    const bool group_contains_curr_hovered_id = (group_data.BackupHoveredIdIsAlive == false) && g.HoveredId != 0;
11388
0
    if (group_contains_curr_hovered_id)
11389
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
11390
11391
    // Forward Edited flag
11392
0
    if (group_contains_curr_active_id && g.ActiveIdHasBeenEditedThisFrame)
11393
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
11394
11395
    // Forward Deactivated flag
11396
0
    g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDeactivated;
11397
0
    if (group_contains_prev_active_id && g.ActiveId != g.ActiveIdPreviousFrame)
11398
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Deactivated;
11399
11400
0
    g.GroupStack.pop_back();
11401
0
    if (g.DebugShowGroupRects)
11402
0
        window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255));   // [Debug]
11403
0
}
11404
11405
11406
//-----------------------------------------------------------------------------
11407
// [SECTION] SCROLLING
11408
//-----------------------------------------------------------------------------
11409
11410
// Helper to snap on edges when aiming at an item very close to the edge,
11411
// So the difference between WindowPadding and ItemSpacing will be in the visible area after scrolling.
11412
// When we refactor the scrolling API this may be configurable with a flag?
11413
// Note that the effect for this won't be visible on X axis with default Style settings as WindowPadding.x == ItemSpacing.x by default.
11414
static float CalcScrollEdgeSnap(float target, float snap_min, float snap_max, float snap_threshold, float center_ratio)
11415
0
{
11416
0
    if (target <= snap_min + snap_threshold)
11417
0
        return ImLerp(snap_min, target, center_ratio);
11418
0
    if (target >= snap_max - snap_threshold)
11419
0
        return ImLerp(target, snap_max, center_ratio);
11420
0
    return target;
11421
0
}
11422
11423
static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window)
11424
193k
{
11425
193k
    ImVec2 scroll = window->Scroll;
11426
193k
    ImVec2 decoration_size(window->DecoOuterSizeX1 + window->DecoInnerSizeX1 + window->DecoOuterSizeX2, window->DecoOuterSizeY1 + window->DecoInnerSizeY1 + window->DecoOuterSizeY2);
11427
581k
    for (int axis = 0; axis < 2; axis++)
11428
387k
    {
11429
387k
        if (window->ScrollTarget[axis] < FLT_MAX)
11430
15.4k
        {
11431
15.4k
            float center_ratio = window->ScrollTargetCenterRatio[axis];
11432
15.4k
            float scroll_target = window->ScrollTarget[axis];
11433
15.4k
            if (window->ScrollTargetEdgeSnapDist[axis] > 0.0f)
11434
0
            {
11435
0
                float snap_min = 0.0f;
11436
0
                float snap_max = window->ScrollMax[axis] + window->SizeFull[axis] - decoration_size[axis];
11437
0
                scroll_target = CalcScrollEdgeSnap(scroll_target, snap_min, snap_max, window->ScrollTargetEdgeSnapDist[axis], center_ratio);
11438
0
            }
11439
15.4k
            scroll[axis] = scroll_target - center_ratio * (window->SizeFull[axis] - decoration_size[axis]);
11440
15.4k
        }
11441
387k
        scroll[axis] = IM_ROUND(ImMax(scroll[axis], 0.0f));
11442
387k
        if (!window->Collapsed && !window->SkipItems)
11443
264k
            scroll[axis] = ImMin(scroll[axis], window->ScrollMax[axis]);
11444
387k
    }
11445
193k
    return scroll;
11446
193k
}
11447
11448
void ImGui::ScrollToItem(ImGuiScrollFlags flags)
11449
0
{
11450
0
    ImGuiContext& g = *GImGui;
11451
0
    ImGuiWindow* window = g.CurrentWindow;
11452
0
    ScrollToRectEx(window, g.LastItemData.NavRect, flags);
11453
0
}
11454
11455
void ImGui::ScrollToRect(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
11456
0
{
11457
0
    ScrollToRectEx(window, item_rect, flags);
11458
0
}
11459
11460
// Scroll to keep newly navigated item fully into view
11461
ImVec2 ImGui::ScrollToRectEx(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
11462
42
{
11463
42
    ImGuiContext& g = *GImGui;
11464
42
    ImRect scroll_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1));
11465
42
    scroll_rect.Min.x = ImMin(scroll_rect.Min.x + window->DecoInnerSizeX1, scroll_rect.Max.x);
11466
42
    scroll_rect.Min.y = ImMin(scroll_rect.Min.y + window->DecoInnerSizeY1, scroll_rect.Max.y);
11467
    //GetForegroundDrawList(window)->AddRect(item_rect.Min, item_rect.Max, IM_COL32(255,0,0,255), 0.0f, 0, 5.0f); // [DEBUG]
11468
    //GetForegroundDrawList(window)->AddRect(scroll_rect.Min, scroll_rect.Max, IM_COL32_WHITE); // [DEBUG]
11469
11470
    // Check that only one behavior is selected per axis
11471
42
    IM_ASSERT((flags & ImGuiScrollFlags_MaskX_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskX_));
11472
42
    IM_ASSERT((flags & ImGuiScrollFlags_MaskY_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskY_));
11473
11474
    // Defaults
11475
42
    ImGuiScrollFlags in_flags = flags;
11476
42
    if ((flags & ImGuiScrollFlags_MaskX_) == 0 && window->ScrollbarX)
11477
0
        flags |= ImGuiScrollFlags_KeepVisibleEdgeX;
11478
42
    if ((flags & ImGuiScrollFlags_MaskY_) == 0)
11479
30
        flags |= window->Appearing ? ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeY;
11480
11481
42
    const bool fully_visible_x = item_rect.Min.x >= scroll_rect.Min.x && item_rect.Max.x <= scroll_rect.Max.x;
11482
42
    const bool fully_visible_y = item_rect.Min.y >= scroll_rect.Min.y && item_rect.Max.y <= scroll_rect.Max.y;
11483
42
    const bool can_be_fully_visible_x = (item_rect.GetWidth() + g.Style.ItemSpacing.x * 2.0f) <= scroll_rect.GetWidth() || (window->AutoFitFramesX > 0) || (window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0;
11484
42
    const bool can_be_fully_visible_y = (item_rect.GetHeight() + g.Style.ItemSpacing.y * 2.0f) <= scroll_rect.GetHeight() || (window->AutoFitFramesY > 0) || (window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0;
11485
11486
42
    if ((flags & ImGuiScrollFlags_KeepVisibleEdgeX) && !fully_visible_x)
11487
0
    {
11488
0
        if (item_rect.Min.x < scroll_rect.Min.x || !can_be_fully_visible_x)
11489
0
            SetScrollFromPosX(window, item_rect.Min.x - g.Style.ItemSpacing.x - window->Pos.x, 0.0f);
11490
0
        else if (item_rect.Max.x >= scroll_rect.Max.x)
11491
0
            SetScrollFromPosX(window, item_rect.Max.x + g.Style.ItemSpacing.x - window->Pos.x, 1.0f);
11492
0
    }
11493
42
    else if (((flags & ImGuiScrollFlags_KeepVisibleCenterX) && !fully_visible_x) || (flags & ImGuiScrollFlags_AlwaysCenterX))
11494
0
    {
11495
0
        if (can_be_fully_visible_x)
11496
0
            SetScrollFromPosX(window, ImTrunc((item_rect.Min.x + item_rect.Max.x) * 0.5f) - window->Pos.x, 0.5f);
11497
0
        else
11498
0
            SetScrollFromPosX(window, item_rect.Min.x - window->Pos.x, 0.0f);
11499
0
    }
11500
11501
42
    if ((flags & ImGuiScrollFlags_KeepVisibleEdgeY) && !fully_visible_y)
11502
0
    {
11503
0
        if (item_rect.Min.y < scroll_rect.Min.y || !can_be_fully_visible_y)
11504
0
            SetScrollFromPosY(window, item_rect.Min.y - g.Style.ItemSpacing.y - window->Pos.y, 0.0f);
11505
0
        else if (item_rect.Max.y >= scroll_rect.Max.y)
11506
0
            SetScrollFromPosY(window, item_rect.Max.y + g.Style.ItemSpacing.y - window->Pos.y, 1.0f);
11507
0
    }
11508
42
    else if (((flags & ImGuiScrollFlags_KeepVisibleCenterY) && !fully_visible_y) || (flags & ImGuiScrollFlags_AlwaysCenterY))
11509
0
    {
11510
0
        if (can_be_fully_visible_y)
11511
0
            SetScrollFromPosY(window, ImTrunc((item_rect.Min.y + item_rect.Max.y) * 0.5f) - window->Pos.y, 0.5f);
11512
0
        else
11513
0
            SetScrollFromPosY(window, item_rect.Min.y - window->Pos.y, 0.0f);
11514
0
    }
11515
11516
42
    ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
11517
42
    ImVec2 delta_scroll = next_scroll - window->Scroll;
11518
11519
    // Also scroll parent window to keep us into view if necessary
11520
42
    if (!(flags & ImGuiScrollFlags_NoScrollParent) && (window->Flags & ImGuiWindowFlags_ChildWindow))
11521
0
    {
11522
        // FIXME-SCROLL: May be an option?
11523
0
        if ((in_flags & (ImGuiScrollFlags_AlwaysCenterX | ImGuiScrollFlags_KeepVisibleCenterX)) != 0)
11524
0
            in_flags = (in_flags & ~ImGuiScrollFlags_MaskX_) | ImGuiScrollFlags_KeepVisibleEdgeX;
11525
0
        if ((in_flags & (ImGuiScrollFlags_AlwaysCenterY | ImGuiScrollFlags_KeepVisibleCenterY)) != 0)
11526
0
            in_flags = (in_flags & ~ImGuiScrollFlags_MaskY_) | ImGuiScrollFlags_KeepVisibleEdgeY;
11527
0
        delta_scroll += ScrollToRectEx(window->ParentWindow, ImRect(item_rect.Min - delta_scroll, item_rect.Max - delta_scroll), in_flags);
11528
0
    }
11529
11530
42
    return delta_scroll;
11531
42
}
11532
11533
float ImGui::GetScrollX()
11534
32.8k
{
11535
32.8k
    ImGuiWindow* window = GImGui->CurrentWindow;
11536
32.8k
    return window->Scroll.x;
11537
32.8k
}
11538
11539
float ImGui::GetScrollY()
11540
32.8k
{
11541
32.8k
    ImGuiWindow* window = GImGui->CurrentWindow;
11542
32.8k
    return window->Scroll.y;
11543
32.8k
}
11544
11545
float ImGui::GetScrollMaxX()
11546
0
{
11547
0
    ImGuiWindow* window = GImGui->CurrentWindow;
11548
0
    return window->ScrollMax.x;
11549
0
}
11550
11551
float ImGui::GetScrollMaxY()
11552
0
{
11553
0
    ImGuiWindow* window = GImGui->CurrentWindow;
11554
0
    return window->ScrollMax.y;
11555
0
}
11556
11557
void ImGui::SetScrollX(ImGuiWindow* window, float scroll_x)
11558
7.02k
{
11559
7.02k
    window->ScrollTarget.x = scroll_x;
11560
7.02k
    window->ScrollTargetCenterRatio.x = 0.0f;
11561
7.02k
    window->ScrollTargetEdgeSnapDist.x = 0.0f;
11562
7.02k
}
11563
11564
void ImGui::SetScrollY(ImGuiWindow* window, float scroll_y)
11565
8.64k
{
11566
8.64k
    window->ScrollTarget.y = scroll_y;
11567
8.64k
    window->ScrollTargetCenterRatio.y = 0.0f;
11568
8.64k
    window->ScrollTargetEdgeSnapDist.y = 0.0f;
11569
8.64k
}
11570
11571
void ImGui::SetScrollX(float scroll_x)
11572
6.87k
{
11573
6.87k
    ImGuiContext& g = *GImGui;
11574
6.87k
    SetScrollX(g.CurrentWindow, scroll_x);
11575
6.87k
}
11576
11577
void ImGui::SetScrollY(float scroll_y)
11578
8.29k
{
11579
8.29k
    ImGuiContext& g = *GImGui;
11580
8.29k
    SetScrollY(g.CurrentWindow, scroll_y);
11581
8.29k
}
11582
11583
// Note that a local position will vary depending on initial scroll value,
11584
// This is a little bit confusing so bear with us:
11585
//  - local_pos = (absolution_pos - window->Pos)
11586
//  - So local_x/local_y are 0.0f for a position at the upper-left corner of a window,
11587
//    and generally local_x/local_y are >(padding+decoration) && <(size-padding-decoration) when in the visible area.
11588
//  - They mostly exist because of legacy API.
11589
// Following the rules above, when trying to work with scrolling code, consider that:
11590
//  - SetScrollFromPosY(0.0f) == SetScrollY(0.0f + scroll.y) == has no effect!
11591
//  - SetScrollFromPosY(-scroll.y) == SetScrollY(-scroll.y + scroll.y) == SetScrollY(0.0f) == reset scroll. Of course writing SetScrollY(0.0f) directly then makes more sense
11592
// We store a target position so centering and clamping can occur on the next frame when we are guaranteed to have a known window size
11593
void ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio)
11594
0
{
11595
0
    IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f);
11596
0
    window->ScrollTarget.x = IM_TRUNC(local_x - window->DecoOuterSizeX1 - window->DecoInnerSizeX1 + window->Scroll.x); // Convert local position to scroll offset
11597
0
    window->ScrollTargetCenterRatio.x = center_x_ratio;
11598
0
    window->ScrollTargetEdgeSnapDist.x = 0.0f;
11599
0
}
11600
11601
void ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio)
11602
0
{
11603
0
    IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
11604
0
    window->ScrollTarget.y = IM_TRUNC(local_y - window->DecoOuterSizeY1 - window->DecoInnerSizeY1 + window->Scroll.y); // Convert local position to scroll offset
11605
0
    window->ScrollTargetCenterRatio.y = center_y_ratio;
11606
0
    window->ScrollTargetEdgeSnapDist.y = 0.0f;
11607
0
}
11608
11609
void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio)
11610
0
{
11611
0
    ImGuiContext& g = *GImGui;
11612
0
    SetScrollFromPosX(g.CurrentWindow, local_x, center_x_ratio);
11613
0
}
11614
11615
void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio)
11616
0
{
11617
0
    ImGuiContext& g = *GImGui;
11618
0
    SetScrollFromPosY(g.CurrentWindow, local_y, center_y_ratio);
11619
0
}
11620
11621
// center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item.
11622
void ImGui::SetScrollHereX(float center_x_ratio)
11623
0
{
11624
0
    ImGuiContext& g = *GImGui;
11625
0
    ImGuiWindow* window = g.CurrentWindow;
11626
0
    float spacing_x = ImMax(window->WindowPadding.x, g.Style.ItemSpacing.x);
11627
0
    float target_pos_x = ImLerp(g.LastItemData.Rect.Min.x - spacing_x, g.LastItemData.Rect.Max.x + spacing_x, center_x_ratio);
11628
0
    SetScrollFromPosX(window, target_pos_x - window->Pos.x, center_x_ratio); // Convert from absolute to local pos
11629
11630
    // Tweak: snap on edges when aiming at an item very close to the edge
11631
0
    window->ScrollTargetEdgeSnapDist.x = ImMax(0.0f, window->WindowPadding.x - spacing_x);
11632
0
}
11633
11634
// center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
11635
void ImGui::SetScrollHereY(float center_y_ratio)
11636
0
{
11637
0
    ImGuiContext& g = *GImGui;
11638
0
    ImGuiWindow* window = g.CurrentWindow;
11639
0
    float spacing_y = ImMax(window->WindowPadding.y, g.Style.ItemSpacing.y);
11640
0
    float target_pos_y = ImLerp(window->DC.CursorPosPrevLine.y - spacing_y, window->DC.CursorPosPrevLine.y + window->DC.PrevLineSize.y + spacing_y, center_y_ratio);
11641
0
    SetScrollFromPosY(window, target_pos_y - window->Pos.y, center_y_ratio); // Convert from absolute to local pos
11642
11643
    // Tweak: snap on edges when aiming at an item very close to the edge
11644
0
    window->ScrollTargetEdgeSnapDist.y = ImMax(0.0f, window->WindowPadding.y - spacing_y);
11645
0
}
11646
11647
//-----------------------------------------------------------------------------
11648
// [SECTION] TOOLTIPS
11649
//-----------------------------------------------------------------------------
11650
11651
bool ImGui::BeginTooltip()
11652
0
{
11653
0
    return BeginTooltipEx(ImGuiTooltipFlags_None, ImGuiWindowFlags_None);
11654
0
}
11655
11656
bool ImGui::BeginItemTooltip()
11657
0
{
11658
0
    if (!IsItemHovered(ImGuiHoveredFlags_ForTooltip))
11659
0
        return false;
11660
0
    return BeginTooltipEx(ImGuiTooltipFlags_None, ImGuiWindowFlags_None);
11661
0
}
11662
11663
bool ImGui::BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags extra_window_flags)
11664
0
{
11665
0
    ImGuiContext& g = *GImGui;
11666
11667
0
    if (g.DragDropWithinSource || g.DragDropWithinTarget)
11668
0
    {
11669
        // Drag and Drop tooltips are positioning differently than other tooltips:
11670
        // - offset visibility to increase visibility around mouse.
11671
        // - never clamp within outer viewport boundary.
11672
        // We call SetNextWindowPos() to enforce position and disable clamping.
11673
        // See FindBestWindowPosForPopup() for positionning logic of other tooltips (not drag and drop ones).
11674
        //ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding;
11675
0
        ImVec2 tooltip_pos = g.IO.MousePos + TOOLTIP_DEFAULT_OFFSET * g.Style.MouseCursorScale;
11676
0
        SetNextWindowPos(tooltip_pos);
11677
0
        SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f);
11678
        //PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :(
11679
0
        tooltip_flags |= ImGuiTooltipFlags_OverridePrevious;
11680
0
    }
11681
11682
0
    char window_name[16];
11683
0
    ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", g.TooltipOverrideCount);
11684
0
    if (tooltip_flags & ImGuiTooltipFlags_OverridePrevious)
11685
0
        if (ImGuiWindow* window = FindWindowByName(window_name))
11686
0
            if (window->Active)
11687
0
            {
11688
                // Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one.
11689
0
                SetWindowHiddenAndSkipItemsForCurrentFrame(window);
11690
0
                ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", ++g.TooltipOverrideCount);
11691
0
            }
11692
0
    ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoDocking;
11693
0
    Begin(window_name, NULL, flags | extra_window_flags);
11694
    // 2023-03-09: Added bool return value to the API, but currently always returning true.
11695
    // If this ever returns false we need to update BeginDragDropSource() accordingly.
11696
    //if (!ret)
11697
    //    End();
11698
    //return ret;
11699
0
    return true;
11700
0
}
11701
11702
void ImGui::EndTooltip()
11703
0
{
11704
0
    IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip);   // Mismatched BeginTooltip()/EndTooltip() calls
11705
0
    End();
11706
0
}
11707
11708
void ImGui::SetTooltip(const char* fmt, ...)
11709
0
{
11710
0
    va_list args;
11711
0
    va_start(args, fmt);
11712
0
    SetTooltipV(fmt, args);
11713
0
    va_end(args);
11714
0
}
11715
11716
void ImGui::SetTooltipV(const char* fmt, va_list args)
11717
0
{
11718
0
    if (!BeginTooltipEx(ImGuiTooltipFlags_OverridePrevious, ImGuiWindowFlags_None))
11719
0
        return;
11720
0
    TextV(fmt, args);
11721
0
    EndTooltip();
11722
0
}
11723
11724
// Shortcut to use 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav'.
11725
// Defaults to == ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort when using the mouse.
11726
void ImGui::SetItemTooltip(const char* fmt, ...)
11727
0
{
11728
0
    va_list args;
11729
0
    va_start(args, fmt);
11730
0
    if (IsItemHovered(ImGuiHoveredFlags_ForTooltip))
11731
0
        SetTooltipV(fmt, args);
11732
0
    va_end(args);
11733
0
}
11734
11735
void ImGui::SetItemTooltipV(const char* fmt, va_list args)
11736
0
{
11737
0
    if (IsItemHovered(ImGuiHoveredFlags_ForTooltip))
11738
0
        SetTooltipV(fmt, args);
11739
0
}
11740
11741
11742
//-----------------------------------------------------------------------------
11743
// [SECTION] POPUPS
11744
//-----------------------------------------------------------------------------
11745
11746
// Supported flags: ImGuiPopupFlags_AnyPopupId, ImGuiPopupFlags_AnyPopupLevel
11747
bool ImGui::IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags)
11748
0
{
11749
0
    ImGuiContext& g = *GImGui;
11750
0
    if (popup_flags & ImGuiPopupFlags_AnyPopupId)
11751
0
    {
11752
        // Return true if any popup is open at the current BeginPopup() level of the popup stack
11753
        // This may be used to e.g. test for another popups already opened to handle popups priorities at the same level.
11754
0
        IM_ASSERT(id == 0);
11755
0
        if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
11756
0
            return g.OpenPopupStack.Size > 0;
11757
0
        else
11758
0
            return g.OpenPopupStack.Size > g.BeginPopupStack.Size;
11759
0
    }
11760
0
    else
11761
0
    {
11762
0
        if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
11763
0
        {
11764
            // Return true if the popup is open anywhere in the popup stack
11765
0
            for (ImGuiPopupData& popup_data : g.OpenPopupStack)
11766
0
                if (popup_data.PopupId == id)
11767
0
                    return true;
11768
0
            return false;
11769
0
        }
11770
0
        else
11771
0
        {
11772
            // Return true if the popup is open at the current BeginPopup() level of the popup stack (this is the most-common query)
11773
0
            return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id;
11774
0
        }
11775
0
    }
11776
0
}
11777
11778
bool ImGui::IsPopupOpen(const char* str_id, ImGuiPopupFlags popup_flags)
11779
0
{
11780
0
    ImGuiContext& g = *GImGui;
11781
0
    ImGuiID id = (popup_flags & ImGuiPopupFlags_AnyPopupId) ? 0 : g.CurrentWindow->GetID(str_id);
11782
0
    if ((popup_flags & ImGuiPopupFlags_AnyPopupLevel) && id != 0)
11783
0
        IM_ASSERT(0 && "Cannot use IsPopupOpen() with a string id and ImGuiPopupFlags_AnyPopupLevel."); // But non-string version is legal and used internally
11784
0
    return IsPopupOpen(id, popup_flags);
11785
0
}
11786
11787
// Also see FindBlockingModal(NULL)
11788
ImGuiWindow* ImGui::GetTopMostPopupModal()
11789
254k
{
11790
254k
    ImGuiContext& g = *GImGui;
11791
254k
    for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
11792
0
        if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
11793
0
            if (popup->Flags & ImGuiWindowFlags_Modal)
11794
0
                return popup;
11795
254k
    return NULL;
11796
254k
}
11797
11798
// See Demo->Stacked Modal to confirm what this is for.
11799
ImGuiWindow* ImGui::GetTopMostAndVisiblePopupModal()
11800
84.9k
{
11801
84.9k
    ImGuiContext& g = *GImGui;
11802
84.9k
    for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
11803
0
        if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
11804
0
            if ((popup->Flags & ImGuiWindowFlags_Modal) && IsWindowActiveAndVisible(popup))
11805
0
                return popup;
11806
84.9k
    return NULL;
11807
84.9k
}
11808
11809
void ImGui::OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags)
11810
0
{
11811
0
    ImGuiContext& g = *GImGui;
11812
0
    ImGuiID id = g.CurrentWindow->GetID(str_id);
11813
0
    IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopup(\"%s\" -> 0x%08X)\n", str_id, id);
11814
0
    OpenPopupEx(id, popup_flags);
11815
0
}
11816
11817
void ImGui::OpenPopup(ImGuiID id, ImGuiPopupFlags popup_flags)
11818
0
{
11819
0
    OpenPopupEx(id, popup_flags);
11820
0
}
11821
11822
// Mark popup as open (toggle toward open state).
11823
// Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block.
11824
// Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
11825
// One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL)
11826
void ImGui::OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags)
11827
0
{
11828
0
    ImGuiContext& g = *GImGui;
11829
0
    ImGuiWindow* parent_window = g.CurrentWindow;
11830
0
    const int current_stack_size = g.BeginPopupStack.Size;
11831
11832
0
    if (popup_flags & ImGuiPopupFlags_NoOpenOverExistingPopup)
11833
0
        if (IsPopupOpen((ImGuiID)0, ImGuiPopupFlags_AnyPopupId))
11834
0
            return;
11835
11836
0
    ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack.
11837
0
    popup_ref.PopupId = id;
11838
0
    popup_ref.Window = NULL;
11839
0
    popup_ref.RestoreNavWindow = g.NavWindow;           // When popup closes focus may be restored to NavWindow (depend on window type).
11840
0
    popup_ref.OpenFrameCount = g.FrameCount;
11841
0
    popup_ref.OpenParentId = parent_window->IDStack.back();
11842
0
    popup_ref.OpenPopupPos = NavCalcPreferredRefPos();
11843
0
    popup_ref.OpenMousePos = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos;
11844
11845
0
    IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopupEx(0x%08X)\n", id);
11846
0
    if (g.OpenPopupStack.Size < current_stack_size + 1)
11847
0
    {
11848
0
        g.OpenPopupStack.push_back(popup_ref);
11849
0
    }
11850
0
    else
11851
0
    {
11852
        // Gently handle the user mistakenly calling OpenPopup() every frames: it is likely a programming mistake!
11853
        // However, if we were to run the regular code path, the ui would become completely unusable because the popup will always be
11854
        // in hidden-while-calculating-size state _while_ claiming focus. Which is extremely confusing situation for the programmer.
11855
        // Instead, for successive frames calls to OpenPopup(), we silently avoid reopening even if ImGuiPopupFlags_NoReopen is not specified.
11856
0
        bool keep_existing = false;
11857
0
        if (g.OpenPopupStack[current_stack_size].PopupId == id)
11858
0
            if ((g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1) || (popup_flags & ImGuiPopupFlags_NoReopen))
11859
0
                keep_existing = true;
11860
0
        if (keep_existing)
11861
0
        {
11862
            // No reopen
11863
0
            g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount;
11864
0
        }
11865
0
        else
11866
0
        {
11867
            // Reopen: close child popups if any, then flag popup for open/reopen (set position, focus, init navigation)
11868
0
            ClosePopupToLevel(current_stack_size, true);
11869
0
            g.OpenPopupStack.push_back(popup_ref);
11870
0
        }
11871
11872
        // When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow().
11873
        // This is equivalent to what ClosePopupToLevel() does.
11874
        //if (g.OpenPopupStack[current_stack_size].PopupId == id)
11875
        //    FocusWindow(parent_window);
11876
0
    }
11877
0
}
11878
11879
// When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
11880
// This function closes any popups that are over 'ref_window'.
11881
void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup)
11882
9.63k
{
11883
9.63k
    ImGuiContext& g = *GImGui;
11884
9.63k
    if (g.OpenPopupStack.Size == 0)
11885
9.63k
        return;
11886
11887
    // Don't close our own child popup windows.
11888
    //IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\") restore_under=%d\n", ref_window ? ref_window->Name : "<NULL>", restore_focus_to_window_under_popup);
11889
0
    int popup_count_to_keep = 0;
11890
0
    if (ref_window)
11891
0
    {
11892
        // Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow)
11893
0
        for (; popup_count_to_keep < g.OpenPopupStack.Size; popup_count_to_keep++)
11894
0
        {
11895
0
            ImGuiPopupData& popup = g.OpenPopupStack[popup_count_to_keep];
11896
0
            if (!popup.Window)
11897
0
                continue;
11898
0
            IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
11899
11900
            // Trim the stack unless the popup is a direct parent of the reference window (the reference window is often the NavWindow)
11901
            // - Clicking/Focusing Window2 won't close Popup1:
11902
            //     Window -> Popup1 -> Window2(Ref)
11903
            // - Clicking/focusing Popup1 will close Popup2 and Popup3:
11904
            //     Window -> Popup1(Ref) -> Popup2 -> Popup3
11905
            // - Each popups may contain child windows, which is why we compare ->RootWindowDockTree!
11906
            //     Window -> Popup1 -> Popup1_Child -> Popup2 -> Popup2_Child
11907
            // We step through every popup from bottom to top to validate their position relative to reference window.
11908
0
            bool ref_window_is_descendent_of_popup = false;
11909
0
            for (int n = popup_count_to_keep; n < g.OpenPopupStack.Size; n++)
11910
0
                if (ImGuiWindow* popup_window = g.OpenPopupStack[n].Window)
11911
                    //if (popup_window->RootWindowDockTree == ref_window->RootWindowDockTree) // FIXME-MERGE
11912
0
                    if (IsWindowWithinBeginStackOf(ref_window, popup_window))
11913
0
                    {
11914
0
                        ref_window_is_descendent_of_popup = true;
11915
0
                        break;
11916
0
                    }
11917
0
            if (!ref_window_is_descendent_of_popup)
11918
0
                break;
11919
0
        }
11920
0
    }
11921
0
    if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
11922
0
    {
11923
0
        IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\")\n", ref_window ? ref_window->Name : "<NULL>");
11924
0
        ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup);
11925
0
    }
11926
0
}
11927
11928
void ImGui::ClosePopupsExceptModals()
11929
0
{
11930
0
    ImGuiContext& g = *GImGui;
11931
11932
0
    int popup_count_to_keep;
11933
0
    for (popup_count_to_keep = g.OpenPopupStack.Size; popup_count_to_keep > 0; popup_count_to_keep--)
11934
0
    {
11935
0
        ImGuiWindow* window = g.OpenPopupStack[popup_count_to_keep - 1].Window;
11936
0
        if (!window || (window->Flags & ImGuiWindowFlags_Modal))
11937
0
            break;
11938
0
    }
11939
0
    if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
11940
0
        ClosePopupToLevel(popup_count_to_keep, true);
11941
0
}
11942
11943
void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup)
11944
0
{
11945
0
    ImGuiContext& g = *GImGui;
11946
0
    IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupToLevel(%d), restore_under=%d\n", remaining, restore_focus_to_window_under_popup);
11947
0
    IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size);
11948
11949
    // Trim open popup stack
11950
0
    ImGuiPopupData prev_popup = g.OpenPopupStack[remaining];
11951
0
    g.OpenPopupStack.resize(remaining);
11952
11953
    // Restore focus (unless popup window was not yet submitted, and didn't have a chance to take focus anyhow. See #7325 for an edge case)
11954
0
    if (restore_focus_to_window_under_popup && prev_popup.Window)
11955
0
    {
11956
0
        ImGuiWindow* popup_window = prev_popup.Window;
11957
0
        ImGuiWindow* focus_window = (popup_window->Flags & ImGuiWindowFlags_ChildMenu) ? popup_window->ParentWindow : prev_popup.RestoreNavWindow;
11958
0
        if (focus_window && !focus_window->WasActive)
11959
0
            FocusTopMostWindowUnderOne(popup_window, NULL, NULL, ImGuiFocusRequestFlags_RestoreFocusedChild); // Fallback
11960
0
        else
11961
0
            FocusWindow(focus_window, (g.NavLayer == ImGuiNavLayer_Main) ? ImGuiFocusRequestFlags_RestoreFocusedChild : ImGuiFocusRequestFlags_None);
11962
0
    }
11963
0
}
11964
11965
// Close the popup we have begin-ed into.
11966
void ImGui::CloseCurrentPopup()
11967
0
{
11968
0
    ImGuiContext& g = *GImGui;
11969
0
    int popup_idx = g.BeginPopupStack.Size - 1;
11970
0
    if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.BeginPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
11971
0
        return;
11972
11973
    // Closing a menu closes its top-most parent popup (unless a modal)
11974
0
    while (popup_idx > 0)
11975
0
    {
11976
0
        ImGuiWindow* popup_window = g.OpenPopupStack[popup_idx].Window;
11977
0
        ImGuiWindow* parent_popup_window = g.OpenPopupStack[popup_idx - 1].Window;
11978
0
        bool close_parent = false;
11979
0
        if (popup_window && (popup_window->Flags & ImGuiWindowFlags_ChildMenu))
11980
0
            if (parent_popup_window && !(parent_popup_window->Flags & ImGuiWindowFlags_MenuBar))
11981
0
                close_parent = true;
11982
0
        if (!close_parent)
11983
0
            break;
11984
0
        popup_idx--;
11985
0
    }
11986
0
    IMGUI_DEBUG_LOG_POPUP("[popup] CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx);
11987
0
    ClosePopupToLevel(popup_idx, true);
11988
11989
    // A common pattern is to close a popup when selecting a menu item/selectable that will open another window.
11990
    // To improve this usage pattern, we avoid nav highlight for a single frame in the parent window.
11991
    // Similarly, we could avoid mouse hover highlight in this window but it is less visually problematic.
11992
0
    if (ImGuiWindow* window = g.NavWindow)
11993
0
        window->DC.NavHideHighlightOneFrame = true;
11994
0
}
11995
11996
// Attention! BeginPopup() adds default flags when calling BeginPopupEx()!
11997
bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_window_flags)
11998
0
{
11999
0
    ImGuiContext& g = *GImGui;
12000
0
    if (!IsPopupOpen(id, ImGuiPopupFlags_None))
12001
0
    {
12002
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
12003
0
        return false;
12004
0
    }
12005
12006
0
    char name[20];
12007
0
    if (extra_window_flags & ImGuiWindowFlags_ChildMenu)
12008
0
        ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.BeginMenuDepth); // Recycle windows based on depth
12009
0
    else
12010
0
        ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame
12011
12012
0
    bool is_open = Begin(name, NULL, extra_window_flags | ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoDocking);
12013
0
    if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
12014
0
        EndPopup();
12015
12016
    //g.CurrentWindow->FocusRouteParentWindow = g.CurrentWindow->ParentWindowInBeginStack;
12017
12018
0
    return is_open;
12019
0
}
12020
12021
bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags)
12022
0
{
12023
0
    ImGuiContext& g = *GImGui;
12024
0
    if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) // Early out for performance
12025
0
    {
12026
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
12027
0
        return false;
12028
0
    }
12029
0
    flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings;
12030
0
    ImGuiID id = g.CurrentWindow->GetID(str_id);
12031
0
    return BeginPopupEx(id, flags);
12032
0
}
12033
12034
// If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup.
12035
// Note that popup visibility status is owned by Dear ImGui (and manipulated with e.g. OpenPopup).
12036
// - *p_open set back to false in BeginPopupModal() when popup is not open.
12037
// - if you set *p_open to false before calling BeginPopupModal(), it will close the popup.
12038
bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags)
12039
0
{
12040
0
    ImGuiContext& g = *GImGui;
12041
0
    ImGuiWindow* window = g.CurrentWindow;
12042
0
    const ImGuiID id = window->GetID(name);
12043
0
    if (!IsPopupOpen(id, ImGuiPopupFlags_None))
12044
0
    {
12045
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
12046
0
        if (p_open && *p_open)
12047
0
            *p_open = false;
12048
0
        return false;
12049
0
    }
12050
12051
    // Center modal windows by default for increased visibility
12052
    // (this won't really last as settings will kick in, and is mostly for backward compatibility. user may do the same themselves)
12053
    // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.
12054
0
    if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0)
12055
0
    {
12056
0
        const ImGuiViewport* viewport = window->WasActive ? window->Viewport : GetMainViewport(); // FIXME-VIEWPORT: What may be our reference viewport?
12057
0
        SetNextWindowPos(viewport->GetCenter(), ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f));
12058
0
    }
12059
12060
0
    flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking;
12061
0
    const bool is_open = Begin(name, p_open, flags);
12062
0
    if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
12063
0
    {
12064
0
        EndPopup();
12065
0
        if (is_open)
12066
0
            ClosePopupToLevel(g.BeginPopupStack.Size, true);
12067
0
        return false;
12068
0
    }
12069
0
    return is_open;
12070
0
}
12071
12072
void ImGui::EndPopup()
12073
0
{
12074
0
    ImGuiContext& g = *GImGui;
12075
0
    ImGuiWindow* window = g.CurrentWindow;
12076
0
    IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup);  // Mismatched BeginPopup()/EndPopup() calls
12077
0
    IM_ASSERT(g.BeginPopupStack.Size > 0);
12078
12079
    // Make all menus and popups wrap around for now, may need to expose that policy (e.g. focus scope could include wrap/loop policy flags used by new move requests)
12080
0
    if (g.NavWindow == window)
12081
0
        NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_LoopY);
12082
12083
    // Child-popups don't need to be laid out
12084
0
    IM_ASSERT(g.WithinEndChild == false);
12085
0
    if (window->Flags & ImGuiWindowFlags_ChildWindow)
12086
0
        g.WithinEndChild = true;
12087
0
    End();
12088
0
    g.WithinEndChild = false;
12089
0
}
12090
12091
// Helper to open a popup if mouse button is released over the item
12092
// - This is essentially the same as BeginPopupContextItem() but without the trailing BeginPopup()
12093
void ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiPopupFlags popup_flags)
12094
0
{
12095
0
    ImGuiContext& g = *GImGui;
12096
0
    ImGuiWindow* window = g.CurrentWindow;
12097
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
12098
0
    if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
12099
0
    {
12100
0
        ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID;    // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
12101
0
        IM_ASSERT(id != 0);                                             // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
12102
0
        OpenPopupEx(id, popup_flags);
12103
0
    }
12104
0
}
12105
12106
// This is a helper to handle the simplest case of associating one named popup to one given widget.
12107
// - To create a popup associated to the last item, you generally want to pass a NULL value to str_id.
12108
// - To create a popup with a specific identifier, pass it in str_id.
12109
//    - This is useful when using using BeginPopupContextItem() on an item which doesn't have an identifier, e.g. a Text() call.
12110
//    - This is useful when multiple code locations may want to manipulate/open the same popup, given an explicit id.
12111
// - You may want to handle the whole on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters).
12112
//   This is essentially the same as:
12113
//       id = str_id ? GetID(str_id) : GetItemID();
12114
//       OpenPopupOnItemClick(str_id, ImGuiPopupFlags_MouseButtonRight);
12115
//       return BeginPopup(id);
12116
//   Which is essentially the same as:
12117
//       id = str_id ? GetID(str_id) : GetItemID();
12118
//       if (IsItemHovered() && IsMouseReleased(ImGuiMouseButton_Right))
12119
//           OpenPopup(id);
12120
//       return BeginPopup(id);
12121
//   The main difference being that this is tweaked to avoid computing the ID twice.
12122
bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags)
12123
0
{
12124
0
    ImGuiContext& g = *GImGui;
12125
0
    ImGuiWindow* window = g.CurrentWindow;
12126
0
    if (window->SkipItems)
12127
0
        return false;
12128
0
    ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID;    // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
12129
0
    IM_ASSERT(id != 0);                                             // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
12130
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
12131
0
    if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
12132
0
        OpenPopupEx(id, popup_flags);
12133
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
12134
0
}
12135
12136
bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiPopupFlags popup_flags)
12137
0
{
12138
0
    ImGuiContext& g = *GImGui;
12139
0
    ImGuiWindow* window = g.CurrentWindow;
12140
0
    if (!str_id)
12141
0
        str_id = "window_context";
12142
0
    ImGuiID id = window->GetID(str_id);
12143
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
12144
0
    if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
12145
0
        if (!(popup_flags & ImGuiPopupFlags_NoOpenOverItems) || !IsAnyItemHovered())
12146
0
            OpenPopupEx(id, popup_flags);
12147
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
12148
0
}
12149
12150
bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiPopupFlags popup_flags)
12151
0
{
12152
0
    ImGuiContext& g = *GImGui;
12153
0
    ImGuiWindow* window = g.CurrentWindow;
12154
0
    if (!str_id)
12155
0
        str_id = "void_context";
12156
0
    ImGuiID id = window->GetID(str_id);
12157
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
12158
0
    if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow))
12159
0
        if (GetTopMostPopupModal() == NULL)
12160
0
            OpenPopupEx(id, popup_flags);
12161
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
12162
0
}
12163
12164
// r_avoid = the rectangle to avoid (e.g. for tooltip it is a rectangle around the mouse cursor which we want to avoid. for popups it's a small point around the cursor.)
12165
// r_outer = the visible area rectangle, minus safe area padding. If our popup size won't fit because of safe area padding we ignore it.
12166
// (r_outer is usually equivalent to the viewport rectangle minus padding, but when multi-viewports are enabled and monitor
12167
//  information are available, it may represent the entire platform monitor from the frame of reference of the current viewport.
12168
//  this allows us to have tooltips/popups displayed out of the parent viewport.)
12169
ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy)
12170
0
{
12171
0
    ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size);
12172
    //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));
12173
    //GetForegroundDrawList()->AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255));
12174
12175
    // Combo Box policy (we want a connecting edge)
12176
0
    if (policy == ImGuiPopupPositionPolicy_ComboBox)
12177
0
    {
12178
0
        const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up };
12179
0
        for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
12180
0
        {
12181
0
            const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
12182
0
            if (n != -1 && dir == *last_dir) // Already tried this direction?
12183
0
                continue;
12184
0
            ImVec2 pos;
12185
0
            if (dir == ImGuiDir_Down)  pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y);          // Below, Toward Right (default)
12186
0
            if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right
12187
0
            if (dir == ImGuiDir_Left)  pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left
12188
0
            if (dir == ImGuiDir_Up)    pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left
12189
0
            if (!r_outer.Contains(ImRect(pos, pos + size)))
12190
0
                continue;
12191
0
            *last_dir = dir;
12192
0
            return pos;
12193
0
        }
12194
0
    }
12195
12196
    // Tooltip and Default popup policy
12197
    // (Always first try the direction we used on the last frame, if any)
12198
0
    if (policy == ImGuiPopupPositionPolicy_Tooltip || policy == ImGuiPopupPositionPolicy_Default)
12199
0
    {
12200
0
        const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left };
12201
0
        for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
12202
0
        {
12203
0
            const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
12204
0
            if (n != -1 && dir == *last_dir) // Already tried this direction?
12205
0
                continue;
12206
12207
0
            const float avail_w = (dir == ImGuiDir_Left ? r_avoid.Min.x : r_outer.Max.x) - (dir == ImGuiDir_Right ? r_avoid.Max.x : r_outer.Min.x);
12208
0
            const float avail_h = (dir == ImGuiDir_Up ? r_avoid.Min.y : r_outer.Max.y) - (dir == ImGuiDir_Down ? r_avoid.Max.y : r_outer.Min.y);
12209
12210
            // If there's not enough room on one axis, there's no point in positioning on a side on this axis (e.g. when not enough width, use a top/bottom position to maximize available width)
12211
0
            if (avail_w < size.x && (dir == ImGuiDir_Left || dir == ImGuiDir_Right))
12212
0
                continue;
12213
0
            if (avail_h < size.y && (dir == ImGuiDir_Up || dir == ImGuiDir_Down))
12214
0
                continue;
12215
12216
0
            ImVec2 pos;
12217
0
            pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x;
12218
0
            pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y;
12219
12220
            // Clamp top-left corner of popup
12221
0
            pos.x = ImMax(pos.x, r_outer.Min.x);
12222
0
            pos.y = ImMax(pos.y, r_outer.Min.y);
12223
12224
0
            *last_dir = dir;
12225
0
            return pos;
12226
0
        }
12227
0
    }
12228
12229
    // Fallback when not enough room:
12230
0
    *last_dir = ImGuiDir_None;
12231
12232
    // For tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
12233
0
    if (policy == ImGuiPopupPositionPolicy_Tooltip)
12234
0
        return ref_pos + ImVec2(2, 2);
12235
12236
    // Otherwise try to keep within display
12237
0
    ImVec2 pos = ref_pos;
12238
0
    pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x);
12239
0
    pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y);
12240
0
    return pos;
12241
0
}
12242
12243
// Note that this is used for popups, which can overlap the non work-area of individual viewports.
12244
ImRect ImGui::GetPopupAllowedExtentRect(ImGuiWindow* window)
12245
0
{
12246
0
    ImGuiContext& g = *GImGui;
12247
0
    ImRect r_screen;
12248
0
    if (window->ViewportAllowPlatformMonitorExtend >= 0)
12249
0
    {
12250
        // Extent with be in the frame of reference of the given viewport (so Min is likely to be negative here)
12251
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[window->ViewportAllowPlatformMonitorExtend];
12252
0
        r_screen.Min = monitor.WorkPos;
12253
0
        r_screen.Max = monitor.WorkPos + monitor.WorkSize;
12254
0
    }
12255
0
    else
12256
0
    {
12257
        // Use the full viewport area (not work area) for popups
12258
0
        r_screen = window->Viewport->GetMainRect();
12259
0
    }
12260
0
    ImVec2 padding = g.Style.DisplaySafeAreaPadding;
12261
0
    r_screen.Expand(ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f));
12262
0
    return r_screen;
12263
0
}
12264
12265
ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
12266
0
{
12267
0
    ImGuiContext& g = *GImGui;
12268
12269
0
    ImRect r_outer = GetPopupAllowedExtentRect(window);
12270
0
    if (window->Flags & ImGuiWindowFlags_ChildMenu)
12271
0
    {
12272
        // Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds.
12273
        // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
12274
0
        ImGuiWindow* parent_window = window->ParentWindow;
12275
0
        float horizontal_overlap = g.Style.ItemInnerSpacing.x; // We want some overlap to convey the relative depth of each menu (currently the amount of overlap is hard-coded to style.ItemSpacing.x).
12276
0
        ImRect r_avoid;
12277
0
        if (parent_window->DC.MenuBarAppending)
12278
0
            r_avoid = ImRect(-FLT_MAX, parent_window->ClipRect.Min.y, FLT_MAX, parent_window->ClipRect.Max.y); // Avoid parent menu-bar. If we wanted multi-line menu-bar, we may instead want to have the calling window setup e.g. a NextWindowData.PosConstraintAvoidRect field
12279
0
        else
12280
0
            r_avoid = ImRect(parent_window->Pos.x + horizontal_overlap, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - horizontal_overlap - parent_window->ScrollbarSizes.x, FLT_MAX);
12281
0
        return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Default);
12282
0
    }
12283
0
    if (window->Flags & ImGuiWindowFlags_Popup)
12284
0
    {
12285
0
        return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, ImRect(window->Pos, window->Pos), ImGuiPopupPositionPolicy_Default); // Ideally we'd disable r_avoid here
12286
0
    }
12287
0
    if (window->Flags & ImGuiWindowFlags_Tooltip)
12288
0
    {
12289
        // Position tooltip (always follows mouse + clamp within outer boundaries)
12290
        // Note that drag and drop tooltips are NOT using this path: BeginTooltipEx() manually sets their position.
12291
        // In theory we could handle both cases in same location, but requires a bit of shuffling as drag and drop tooltips are calling SetWindowPos() leading to 'window_pos_set_by_api' being set in Begin()
12292
0
        IM_ASSERT(g.CurrentWindow == window);
12293
0
        const float scale = g.Style.MouseCursorScale;
12294
0
        const ImVec2 ref_pos = NavCalcPreferredRefPos();
12295
0
        const ImVec2 tooltip_pos = ref_pos + TOOLTIP_DEFAULT_OFFSET * scale;
12296
0
        ImRect r_avoid;
12297
0
        if (!g.NavDisableHighlight && g.NavDisableMouseHover && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos))
12298
0
            r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
12299
0
        else
12300
0
            r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24 * scale, ref_pos.y + 24 * scale); // FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important.
12301
        //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255, 0, 255, 255));
12302
0
        return FindBestWindowPosForPopupEx(tooltip_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Tooltip);
12303
0
    }
12304
0
    IM_ASSERT(0);
12305
0
    return window->Pos;
12306
0
}
12307
12308
//-----------------------------------------------------------------------------
12309
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
12310
//-----------------------------------------------------------------------------
12311
12312
// FIXME-NAV: The existence of SetNavID vs SetFocusID vs FocusWindow() needs to be clarified/reworked.
12313
// In our terminology those should be interchangeable, yet right now this is super confusing.
12314
// Those two functions are merely a legacy artifact, so at minimum naming should be clarified.
12315
12316
void ImGui::SetNavWindow(ImGuiWindow* window)
12317
9.59k
{
12318
9.59k
    ImGuiContext& g = *GImGui;
12319
9.59k
    if (g.NavWindow != window)
12320
9.59k
    {
12321
9.59k
        IMGUI_DEBUG_LOG_FOCUS("[focus] SetNavWindow(\"%s\")\n", window ? window->Name : "<NULL>");
12322
9.59k
        g.NavWindow = window;
12323
9.59k
        g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
12324
9.59k
    }
12325
9.59k
    g.NavInitRequest = g.NavMoveSubmitted = g.NavMoveScoringItems = false;
12326
9.59k
    NavUpdateAnyRequestFlag();
12327
9.59k
}
12328
12329
void ImGui::NavHighlightActivated(ImGuiID id)
12330
29
{
12331
29
    ImGuiContext& g = *GImGui;
12332
29
    g.NavHighlightActivatedId = id;
12333
29
    g.NavHighlightActivatedTimer = NAV_ACTIVATE_HIGHLIGHT_TIMER;
12334
29
}
12335
12336
void ImGui::NavClearPreferredPosForAxis(ImGuiAxis axis)
12337
1.60k
{
12338
1.60k
    ImGuiContext& g = *GImGui;
12339
1.60k
    g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer][axis] = FLT_MAX;
12340
1.60k
}
12341
12342
void ImGui::SetNavID(ImGuiID id, ImGuiNavLayer nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel)
12343
512
{
12344
512
    ImGuiContext& g = *GImGui;
12345
512
    IM_ASSERT(g.NavWindow != NULL);
12346
512
    IM_ASSERT(nav_layer == ImGuiNavLayer_Main || nav_layer == ImGuiNavLayer_Menu);
12347
512
    g.NavId = id;
12348
512
    g.NavLayer = nav_layer;
12349
512
    SetNavFocusScope(focus_scope_id);
12350
512
    g.NavWindow->NavLastIds[nav_layer] = id;
12351
512
    g.NavWindow->NavRectRel[nav_layer] = rect_rel;
12352
12353
    // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it)
12354
512
    NavClearPreferredPosForAxis(ImGuiAxis_X);
12355
512
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
12356
512
}
12357
12358
void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
12359
2
{
12360
2
    ImGuiContext& g = *GImGui;
12361
2
    IM_ASSERT(id != 0);
12362
12363
2
    if (g.NavWindow != window)
12364
2
       SetNavWindow(window);
12365
12366
    // Assume that SetFocusID() is called in the context where its window->DC.NavLayerCurrent and g.CurrentFocusScopeId are valid.
12367
    // Note that window may be != g.CurrentWindow (e.g. SetFocusID call in InputTextEx for multi-line text)
12368
2
    const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent;
12369
2
    g.NavId = id;
12370
2
    g.NavLayer = nav_layer;
12371
2
    SetNavFocusScope(g.CurrentFocusScopeId);
12372
2
    window->NavLastIds[nav_layer] = id;
12373
2
    if (g.LastItemData.ID == id)
12374
2
        window->NavRectRel[nav_layer] = WindowRectAbsToRel(window, g.LastItemData.NavRect);
12375
12376
2
    if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad)
12377
1
        g.NavDisableMouseHover = true;
12378
1
    else
12379
1
        g.NavDisableHighlight = true;
12380
12381
    // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it)
12382
2
    NavClearPreferredPosForAxis(ImGuiAxis_X);
12383
2
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
12384
2
}
12385
12386
static ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy)
12387
49
{
12388
49
    if (ImFabs(dx) > ImFabs(dy))
12389
14
        return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left;
12390
35
    return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up;
12391
49
}
12392
12393
static float inline NavScoreItemDistInterval(float cand_min, float cand_max, float curr_min, float curr_max)
12394
110
{
12395
110
    if (cand_max < curr_min)
12396
26
        return cand_max - curr_min;
12397
84
    if (curr_max < cand_min)
12398
9
        return cand_min - curr_max;
12399
75
    return 0.0f;
12400
84
}
12401
12402
// Scoring function for gamepad/keyboard directional navigation. Based on https://gist.github.com/rygorous/6981057
12403
static bool ImGui::NavScoreItem(ImGuiNavItemData* result)
12404
228
{
12405
228
    ImGuiContext& g = *GImGui;
12406
228
    ImGuiWindow* window = g.CurrentWindow;
12407
228
    if (g.NavLayer != window->DC.NavLayerCurrent)
12408
173
        return false;
12409
12410
    // FIXME: Those are not good variables names
12411
55
    ImRect cand = g.LastItemData.NavRect;   // Current item nav rectangle
12412
55
    const ImRect curr = g.NavScoringRect;   // Current modified source rect (NB: we've applied Max.x = Min.x in NavUpdate() to inhibit the effect of having varied item width)
12413
55
    g.NavScoringDebugCount++;
12414
12415
    // When entering through a NavFlattened border, we consider child window items as fully clipped for scoring
12416
55
    if (window->ParentWindow == g.NavWindow)
12417
0
    {
12418
0
        IM_ASSERT((window->ChildFlags | g.NavWindow->ChildFlags) & ImGuiChildFlags_NavFlattened);
12419
0
        if (!window->ClipRect.Overlaps(cand))
12420
0
            return false;
12421
0
        cand.ClipWithFull(window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window
12422
0
    }
12423
12424
    // Compute distance between boxes
12425
    // FIXME-NAV: Introducing biases for vertical navigation, needs to be removed.
12426
55
    float dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x);
12427
55
    float dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2f), ImLerp(cand.Min.y, cand.Max.y, 0.8f), ImLerp(curr.Min.y, curr.Max.y, 0.2f), ImLerp(curr.Min.y, curr.Max.y, 0.8f)); // Scale down on Y to keep using box-distance for vertically touching items
12428
55
    if (dby != 0.0f && dbx != 0.0f)
12429
0
        dbx = (dbx / 1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f);
12430
55
    float dist_box = ImFabs(dbx) + ImFabs(dby);
12431
12432
    // Compute distance between centers (this is off by a factor of 2, but we only compare center distances with each other so it doesn't matter)
12433
55
    float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x);
12434
55
    float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y);
12435
55
    float dist_center = ImFabs(dcx) + ImFabs(dcy); // L1 metric (need this for our connectedness guarantee)
12436
12437
    // Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance
12438
55
    ImGuiDir quadrant;
12439
55
    float dax = 0.0f, day = 0.0f, dist_axial = 0.0f;
12440
55
    if (dbx != 0.0f || dby != 0.0f)
12441
35
    {
12442
        // For non-overlapping boxes, use distance between boxes
12443
        // FIXME-NAV: Quadrant may be incorrect because of (1) dbx bias and (2) curr.Max.y bias applied by NavBiasScoringRect() where typically curr.Max.y==curr.Min.y
12444
        // One typical case where this happens, with style.WindowMenuButtonPosition == ImGuiDir_Right, pressing Left to navigate from Close to Collapse tends to fail.
12445
        // Also see #6344. Calling ImGetDirQuadrantFromDelta() with unbiased values may be good but side-effects are plenty.
12446
35
        dax = dbx;
12447
35
        day = dby;
12448
35
        dist_axial = dist_box;
12449
35
        quadrant = ImGetDirQuadrantFromDelta(dbx, dby);
12450
35
    }
12451
20
    else if (dcx != 0.0f || dcy != 0.0f)
12452
14
    {
12453
        // For overlapping boxes with different centers, use distance between centers
12454
14
        dax = dcx;
12455
14
        day = dcy;
12456
14
        dist_axial = dist_center;
12457
14
        quadrant = ImGetDirQuadrantFromDelta(dcx, dcy);
12458
14
    }
12459
6
    else
12460
6
    {
12461
        // Degenerate case: two overlapping buttons with same center, break ties arbitrarily (note that LastItemId here is really the _previous_ item order, but it doesn't matter)
12462
6
        quadrant = (g.LastItemData.ID < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right;
12463
6
    }
12464
12465
55
    const ImGuiDir move_dir = g.NavMoveDir;
12466
#if IMGUI_DEBUG_NAV_SCORING
12467
    char buf[200];
12468
    if (g.IO.KeyCtrl) // Hold CTRL to preview score in matching quadrant. CTRL+Arrow to rotate.
12469
    {
12470
        if (quadrant == move_dir)
12471
        {
12472
            ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center);
12473
            ImDrawList* draw_list = GetForegroundDrawList(window);
12474
            draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 80));
12475
            draw_list->AddRectFilled(cand.Min, cand.Min + CalcTextSize(buf), IM_COL32(255, 0, 0, 200));
12476
            draw_list->AddText(cand.Min, IM_COL32(255, 255, 255, 255), buf);
12477
        }
12478
    }
12479
    const bool debug_hovering = IsMouseHoveringRect(cand.Min, cand.Max);
12480
    const bool debug_tty = (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_Space));
12481
    if (debug_hovering || debug_tty)
12482
    {
12483
        ImFormatString(buf, IM_ARRAYSIZE(buf),
12484
            "d-box    (%7.3f,%7.3f) -> %7.3f\nd-center (%7.3f,%7.3f) -> %7.3f\nd-axial  (%7.3f,%7.3f) -> %7.3f\nnav %c, quadrant %c",
12485
            dbx, dby, dist_box, dcx, dcy, dist_center, dax, day, dist_axial, "-WENS"[move_dir+1], "-WENS"[quadrant+1]);
12486
        if (debug_hovering)
12487
        {
12488
            ImDrawList* draw_list = GetForegroundDrawList(window);
12489
            draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255, 200, 0, 100));
12490
            draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255, 255, 0, 200));
12491
            draw_list->AddRectFilled(cand.Max - ImVec2(4, 4), cand.Max + CalcTextSize(buf) + ImVec2(4, 4), IM_COL32(40, 0, 0, 200));
12492
            draw_list->AddText(cand.Max, ~0U, buf);
12493
        }
12494
        if (debug_tty) { IMGUI_DEBUG_LOG_NAV("id 0x%08X\n%s\n", g.LastItemData.ID, buf); }
12495
    }
12496
#endif
12497
12498
    // Is it in the quadrant we're interested in moving to?
12499
55
    bool new_best = false;
12500
55
    if (quadrant == move_dir)
12501
52
    {
12502
        // Does it beat the current best candidate?
12503
52
        if (dist_box < result->DistBox)
12504
52
        {
12505
52
            result->DistBox = dist_box;
12506
52
            result->DistCenter = dist_center;
12507
52
            return true;
12508
52
        }
12509
0
        if (dist_box == result->DistBox)
12510
0
        {
12511
            // Try using distance between center points to break ties
12512
0
            if (dist_center < result->DistCenter)
12513
0
            {
12514
0
                result->DistCenter = dist_center;
12515
0
                new_best = true;
12516
0
            }
12517
0
            else if (dist_center == result->DistCenter)
12518
0
            {
12519
                // Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items
12520
                // (with higher index) to the right/downwards by an infinitesimal amount since we the current "best" button already (so it must have a lower index),
12521
                // this is fairly easy. This rule ensures that all buttons with dx==dy==0 will end up being linked in order of appearance along the x axis.
12522
0
                if (((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance
12523
0
                    new_best = true;
12524
0
            }
12525
0
        }
12526
0
    }
12527
12528
    // Axial check: if 'curr' has no link at all in some direction and 'cand' lies roughly in that direction, add a tentative link. This will only be kept if no "real" matches
12529
    // are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness)
12530
    // This is just to avoid buttons having no links in a particular direction when there's a suitable neighbor. you get good graphs without this too.
12531
    // 2017/09/29: FIXME: This now currently only enabled inside menu bars, ideally we'd disable it everywhere. Menus in particular need to catch failure. For general navigation it feels awkward.
12532
    // Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option?
12533
3
    if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial)  // Check axial match
12534
3
        if (g.NavLayer == ImGuiNavLayer_Menu && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
12535
0
            if ((move_dir == ImGuiDir_Left && dax < 0.0f) || (move_dir == ImGuiDir_Right && dax > 0.0f) || (move_dir == ImGuiDir_Up && day < 0.0f) || (move_dir == ImGuiDir_Down && day > 0.0f))
12536
0
            {
12537
0
                result->DistAxial = dist_axial;
12538
0
                new_best = true;
12539
0
            }
12540
12541
3
    return new_best;
12542
55
}
12543
12544
static void ImGui::NavApplyItemToResult(ImGuiNavItemData* result)
12545
122
{
12546
122
    ImGuiContext& g = *GImGui;
12547
122
    ImGuiWindow* window = g.CurrentWindow;
12548
122
    result->Window = window;
12549
122
    result->ID = g.LastItemData.ID;
12550
122
    result->FocusScopeId = g.CurrentFocusScopeId;
12551
122
    result->InFlags = g.LastItemData.InFlags;
12552
122
    result->RectRel = WindowRectAbsToRel(window, g.LastItemData.NavRect);
12553
122
    if (result->InFlags & ImGuiItemFlags_HasSelectionUserData)
12554
0
    {
12555
0
        IM_ASSERT(g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid);
12556
0
        result->SelectionUserData = g.NextItemData.SelectionUserData; // INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData.
12557
0
    }
12558
122
}
12559
12560
// True when current work location may be scrolled horizontally when moving left / right.
12561
// This is generally always true UNLESS within a column. We don't have a vertical equivalent.
12562
void ImGui::NavUpdateCurrentWindowIsScrollPushableX()
12563
302k
{
12564
302k
    ImGuiContext& g = *GImGui;
12565
302k
    ImGuiWindow* window = g.CurrentWindow;
12566
302k
    window->DC.NavIsScrollPushableX = (g.CurrentTable == NULL && window->DC.CurrentColumns == NULL);
12567
302k
}
12568
12569
// We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above)
12570
// This is called after LastItemData is set, but NextItemData is also still valid.
12571
static void ImGui::NavProcessItem()
12572
2.25k
{
12573
2.25k
    ImGuiContext& g = *GImGui;
12574
2.25k
    ImGuiWindow* window = g.CurrentWindow;
12575
2.25k
    const ImGuiID id = g.LastItemData.ID;
12576
2.25k
    const ImGuiItemFlags item_flags = g.LastItemData.InFlags;
12577
12578
    // When inside a container that isn't scrollable with Left<>Right, clip NavRect accordingly (#2221)
12579
2.25k
    if (window->DC.NavIsScrollPushableX == false)
12580
0
    {
12581
0
        g.LastItemData.NavRect.Min.x = ImClamp(g.LastItemData.NavRect.Min.x, window->ClipRect.Min.x, window->ClipRect.Max.x);
12582
0
        g.LastItemData.NavRect.Max.x = ImClamp(g.LastItemData.NavRect.Max.x, window->ClipRect.Min.x, window->ClipRect.Max.x);
12583
0
    }
12584
2.25k
    const ImRect nav_bb = g.LastItemData.NavRect;
12585
12586
    // Process Init Request
12587
2.25k
    if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent && (item_flags & ImGuiItemFlags_Disabled) == 0)
12588
58
    {
12589
        // Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback
12590
58
        const bool candidate_for_nav_default_focus = (item_flags & ImGuiItemFlags_NoNavDefaultFocus) == 0;
12591
58
        if (candidate_for_nav_default_focus || g.NavInitResult.ID == 0)
12592
58
        {
12593
58
            NavApplyItemToResult(&g.NavInitResult);
12594
58
        }
12595
58
        if (candidate_for_nav_default_focus)
12596
20
        {
12597
20
            g.NavInitRequest = false; // Found a match, clear request
12598
20
            NavUpdateAnyRequestFlag();
12599
20
        }
12600
58
    }
12601
12602
    // Process Move Request (scoring for navigation)
12603
    // FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRect + scoring from a rect wrapped according to current wrapping policy)
12604
2.25k
    if (g.NavMoveScoringItems && (item_flags & ImGuiItemFlags_Disabled) == 0)
12605
285
    {
12606
285
        if ((g.NavMoveFlags & ImGuiNavMoveFlags_FocusApi) || (window->Flags & ImGuiWindowFlags_NoNavInputs) == 0)
12607
285
        {
12608
285
            const bool is_tabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) != 0;
12609
285
            if (is_tabbing)
12610
35
            {
12611
35
                NavProcessItemForTabbingRequest(id, item_flags, g.NavMoveFlags);
12612
35
            }
12613
250
            else if (g.NavId != id || (g.NavMoveFlags & ImGuiNavMoveFlags_AllowCurrentNavId))
12614
185
            {
12615
185
                ImGuiNavItemData* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
12616
185
                if (NavScoreItem(result))
12617
41
                    NavApplyItemToResult(result);
12618
12619
                // Features like PageUp/PageDown need to maintain a separate score for the visible set of items.
12620
185
                const float VISIBLE_RATIO = 0.70f;
12621
185
                if ((g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(nav_bb))
12622
43
                    if (ImClamp(nav_bb.Max.y, window->ClipRect.Min.y, window->ClipRect.Max.y) - ImClamp(nav_bb.Min.y, window->ClipRect.Min.y, window->ClipRect.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO)
12623
43
                        if (NavScoreItem(&g.NavMoveResultLocalVisible))
12624
11
                            NavApplyItemToResult(&g.NavMoveResultLocalVisible);
12625
185
            }
12626
285
        }
12627
285
    }
12628
12629
    // Update information for currently focused/navigated item
12630
2.25k
    if (g.NavId == id)
12631
1.99k
    {
12632
1.99k
        if (g.NavWindow != window)
12633
0
            SetNavWindow(window); // Always refresh g.NavWindow, because some operations such as FocusItem() may not have a window.
12634
1.99k
        g.NavLayer = window->DC.NavLayerCurrent;
12635
1.99k
        SetNavFocusScope(g.CurrentFocusScopeId); // Will set g.NavFocusScopeId AND store g.NavFocusScopePath
12636
1.99k
        g.NavFocusScopeId = g.CurrentFocusScopeId;
12637
1.99k
        g.NavIdIsAlive = true;
12638
1.99k
        if (g.LastItemData.InFlags & ImGuiItemFlags_HasSelectionUserData)
12639
0
        {
12640
0
            IM_ASSERT(g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid);
12641
0
            g.NavLastValidSelectionUserData = g.NextItemData.SelectionUserData; // INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData.
12642
0
        }
12643
1.99k
        window->NavRectRel[window->DC.NavLayerCurrent] = WindowRectAbsToRel(window, nav_bb); // Store item bounding box (relative to window position)
12644
1.99k
    }
12645
2.25k
}
12646
12647
// Handle "scoring" of an item for a tabbing/focusing request initiated by NavUpdateCreateTabbingRequest().
12648
// Note that SetKeyboardFocusHere() API calls are considered tabbing requests!
12649
// - Case 1: no nav/active id:    set result to first eligible item, stop storing.
12650
// - Case 2: tab forward:         on ref id set counter, on counter elapse store result
12651
// - Case 3: tab forward wrap:    set result to first eligible item (preemptively), on ref id set counter, on next frame if counter hasn't elapsed store result. // FIXME-TABBING: Could be done as a next-frame forwarded request
12652
// - Case 4: tab backward:        store all results, on ref id pick prev, stop storing
12653
// - Case 5: tab backward wrap:   store all results, on ref id if no result keep storing until last // FIXME-TABBING: Could be done as next-frame forwarded requested
12654
void ImGui::NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags)
12655
35
{
12656
35
    ImGuiContext& g = *GImGui;
12657
12658
35
    if ((move_flags & ImGuiNavMoveFlags_FocusApi) == 0)
12659
35
    {
12660
35
        if (g.NavLayer != g.CurrentWindow->DC.NavLayerCurrent)
12661
20
            return;
12662
15
        if (g.NavFocusScopeId != g.CurrentFocusScopeId)
12663
3
            return;
12664
15
    }
12665
12666
    // - Can always land on an item when using API call.
12667
    // - Tabbing with _NavEnableKeyboard (space/enter/arrows): goes through every item.
12668
    // - Tabbing without _NavEnableKeyboard: goes through inputable items only.
12669
12
    bool can_stop;
12670
12
    if (move_flags & ImGuiNavMoveFlags_FocusApi)
12671
0
        can_stop = true;
12672
12
    else
12673
12
        can_stop = (item_flags & ImGuiItemFlags_NoTabStop) == 0 && ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) || (item_flags & ImGuiItemFlags_Inputable));
12674
12675
    // Always store in NavMoveResultLocal (unlike directional request which uses NavMoveResultOther on sibling/flattened windows)
12676
12
    ImGuiNavItemData* result = &g.NavMoveResultLocal;
12677
12
    if (g.NavTabbingDir == +1)
12678
12
    {
12679
        // Tab Forward or SetKeyboardFocusHere() with >= 0
12680
12
        if (can_stop && g.NavTabbingResultFirst.ID == 0)
12681
12
            NavApplyItemToResult(&g.NavTabbingResultFirst);
12682
12
        if (can_stop && g.NavTabbingCounter > 0 && --g.NavTabbingCounter == 0)
12683
0
            NavMoveRequestResolveWithLastItem(result);
12684
12
        else if (g.NavId == id)
12685
12
            g.NavTabbingCounter = 1;
12686
12
    }
12687
0
    else if (g.NavTabbingDir == -1)
12688
0
    {
12689
        // Tab Backward
12690
0
        if (g.NavId == id)
12691
0
        {
12692
0
            if (result->ID)
12693
0
            {
12694
0
                g.NavMoveScoringItems = false;
12695
0
                NavUpdateAnyRequestFlag();
12696
0
            }
12697
0
        }
12698
0
        else if (can_stop)
12699
0
        {
12700
            // Keep applying until reaching NavId
12701
0
            NavApplyItemToResult(result);
12702
0
        }
12703
0
    }
12704
0
    else if (g.NavTabbingDir == 0)
12705
0
    {
12706
0
        if (can_stop && g.NavId == id)
12707
0
            NavMoveRequestResolveWithLastItem(result);
12708
0
        if (can_stop && g.NavTabbingResultFirst.ID == 0) // Tab init
12709
0
            NavApplyItemToResult(&g.NavTabbingResultFirst);
12710
0
    }
12711
12
}
12712
12713
bool ImGui::NavMoveRequestButNoResultYet()
12714
18.1k
{
12715
18.1k
    ImGuiContext& g = *GImGui;
12716
18.1k
    return g.NavMoveScoringItems && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0;
12717
18.1k
}
12718
12719
// FIXME: ScoringRect is not set
12720
void ImGui::NavMoveRequestSubmit(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
12721
827
{
12722
827
    ImGuiContext& g = *GImGui;
12723
827
    IM_ASSERT(g.NavWindow != NULL);
12724
    //IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestSubmit: dir %c, window \"%s\"\n", "-WENS"[move_dir + 1], g.NavWindow->Name);
12725
12726
827
    if (move_flags & ImGuiNavMoveFlags_IsTabbing)
12727
75
        move_flags |= ImGuiNavMoveFlags_AllowCurrentNavId;
12728
12729
827
    g.NavMoveSubmitted = g.NavMoveScoringItems = true;
12730
827
    g.NavMoveDir = move_dir;
12731
827
    g.NavMoveDirForDebug = move_dir;
12732
827
    g.NavMoveClipDir = clip_dir;
12733
827
    g.NavMoveFlags = move_flags;
12734
827
    g.NavMoveScrollFlags = scroll_flags;
12735
827
    g.NavMoveForwardToNextFrame = false;
12736
827
    g.NavMoveKeyMods = (move_flags & ImGuiNavMoveFlags_FocusApi) ? 0 : g.IO.KeyMods;
12737
827
    g.NavMoveResultLocal.Clear();
12738
827
    g.NavMoveResultLocalVisible.Clear();
12739
827
    g.NavMoveResultOther.Clear();
12740
827
    g.NavTabbingCounter = 0;
12741
827
    g.NavTabbingResultFirst.Clear();
12742
827
    NavUpdateAnyRequestFlag();
12743
827
}
12744
12745
void ImGui::NavMoveRequestResolveWithLastItem(ImGuiNavItemData* result)
12746
0
{
12747
0
    ImGuiContext& g = *GImGui;
12748
0
    g.NavMoveScoringItems = false; // Ensure request doesn't need more processing
12749
0
    NavApplyItemToResult(result);
12750
0
    NavUpdateAnyRequestFlag();
12751
0
}
12752
12753
// Called by TreePop() to implement ImGuiTreeNodeFlags_NavLeftJumpsBackHere
12754
void ImGui::NavMoveRequestResolveWithPastTreeNode(ImGuiNavItemData* result, ImGuiTreeNodeStackData* tree_node_data)
12755
0
{
12756
0
    ImGuiContext& g = *GImGui;
12757
0
    g.NavMoveScoringItems = false;
12758
0
    g.LastItemData.ID = tree_node_data->ID;
12759
0
    g.LastItemData.InFlags = tree_node_data->InFlags & ~ImGuiItemFlags_HasSelectionUserData; // Losing SelectionUserData, recovered next-frame (cheaper).
12760
0
    g.LastItemData.NavRect = tree_node_data->NavRect;
12761
0
    NavApplyItemToResult(result); // Result this instead of implementing a NavApplyPastTreeNodeToResult()
12762
0
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
12763
0
    NavUpdateAnyRequestFlag();
12764
0
}
12765
12766
void ImGui::NavMoveRequestCancel()
12767
1
{
12768
1
    ImGuiContext& g = *GImGui;
12769
1
    g.NavMoveSubmitted = g.NavMoveScoringItems = false;
12770
1
    NavUpdateAnyRequestFlag();
12771
1
}
12772
12773
// Forward will reuse the move request again on the next frame (generally with modifications done to it)
12774
void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
12775
0
{
12776
0
    ImGuiContext& g = *GImGui;
12777
0
    IM_ASSERT(g.NavMoveForwardToNextFrame == false);
12778
0
    NavMoveRequestCancel();
12779
0
    g.NavMoveForwardToNextFrame = true;
12780
0
    g.NavMoveDir = move_dir;
12781
0
    g.NavMoveClipDir = clip_dir;
12782
0
    g.NavMoveFlags = move_flags | ImGuiNavMoveFlags_Forwarded;
12783
0
    g.NavMoveScrollFlags = scroll_flags;
12784
0
}
12785
12786
// Navigation wrap-around logic is delayed to the end of the frame because this operation is only valid after entire
12787
// popup is assembled and in case of appended popups it is not clear which EndPopup() call is final.
12788
void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags wrap_flags)
12789
0
{
12790
0
    ImGuiContext& g = *GImGui;
12791
0
    IM_ASSERT((wrap_flags & ImGuiNavMoveFlags_WrapMask_ ) != 0 && (wrap_flags & ~ImGuiNavMoveFlags_WrapMask_) == 0); // Call with _WrapX, _WrapY, _LoopX, _LoopY
12792
12793
    // In theory we should test for NavMoveRequestButNoResultYet() but there's no point doing it:
12794
    // as NavEndFrame() will do the same test. It will end up calling NavUpdateCreateWrappingRequest().
12795
0
    if (g.NavWindow == window && g.NavMoveScoringItems && g.NavLayer == ImGuiNavLayer_Main)
12796
0
        g.NavMoveFlags = (g.NavMoveFlags & ~ImGuiNavMoveFlags_WrapMask_) | wrap_flags;
12797
0
}
12798
12799
// FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0).
12800
// This way we could find the last focused window among our children. It would be much less confusing this way?
12801
static void ImGui::NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window)
12802
13.5k
{
12803
13.5k
    ImGuiWindow* parent = nav_window;
12804
25.1k
    while (parent && parent->RootWindow != parent && (parent->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
12805
11.6k
        parent = parent->ParentWindow;
12806
13.5k
    if (parent && parent != nav_window)
12807
11.6k
        parent->NavLastChildNavWindow = nav_window;
12808
13.5k
}
12809
12810
// Restore the last focused child.
12811
// Call when we are expected to land on the Main Layer (0) after FocusWindow()
12812
static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window)
12813
16
{
12814
16
    if (window->NavLastChildNavWindow && window->NavLastChildNavWindow->WasActive)
12815
16
        return window->NavLastChildNavWindow;
12816
0
    if (window->DockNodeAsHost && window->DockNodeAsHost->TabBar)
12817
0
        if (ImGuiTabItem* tab = TabBarFindMostRecentlySelectedTabForActiveWindow(window->DockNodeAsHost->TabBar))
12818
0
            return tab->Window;
12819
0
    return window;
12820
0
}
12821
12822
void ImGui::NavRestoreLayer(ImGuiNavLayer layer)
12823
54
{
12824
54
    ImGuiContext& g = *GImGui;
12825
54
    if (layer == ImGuiNavLayer_Main)
12826
16
    {
12827
16
        ImGuiWindow* prev_nav_window = g.NavWindow;
12828
16
        g.NavWindow = NavRestoreLastChildNavWindow(g.NavWindow);    // FIXME-NAV: Should clear ongoing nav requests?
12829
16
        g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
12830
16
        if (prev_nav_window)
12831
16
            IMGUI_DEBUG_LOG_FOCUS("[focus] NavRestoreLayer: from \"%s\" to SetNavWindow(\"%s\")\n", prev_nav_window->Name, g.NavWindow->Name);
12832
16
    }
12833
54
    ImGuiWindow* window = g.NavWindow;
12834
54
    if (window->NavLastIds[layer] != 0)
12835
4
    {
12836
4
        SetNavID(window->NavLastIds[layer], layer, 0, window->NavRectRel[layer]);
12837
4
    }
12838
50
    else
12839
50
    {
12840
50
        g.NavLayer = layer;
12841
50
        NavInitWindow(window, true);
12842
50
    }
12843
54
}
12844
12845
void ImGui::NavRestoreHighlightAfterMove()
12846
576
{
12847
576
    ImGuiContext& g = *GImGui;
12848
576
    g.NavDisableHighlight = false;
12849
576
    g.NavDisableMouseHover = g.NavMousePosDirty = true;
12850
576
}
12851
12852
static inline void ImGui::NavUpdateAnyRequestFlag()
12853
95.4k
{
12854
95.4k
    ImGuiContext& g = *GImGui;
12855
95.4k
    g.NavAnyRequest = g.NavMoveScoringItems || g.NavInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.NavWindow != NULL);
12856
95.4k
    if (g.NavAnyRequest)
12857
95.4k
        IM_ASSERT(g.NavWindow != NULL);
12858
95.4k
}
12859
12860
// This needs to be called before we submit any widget (aka in or before Begin)
12861
void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)
12862
79
{
12863
    // FIXME: ChildWindow test here is wrong for docking
12864
79
    ImGuiContext& g = *GImGui;
12865
79
    IM_ASSERT(window == g.NavWindow);
12866
12867
79
    if (window->Flags & ImGuiWindowFlags_NoNavInputs)
12868
0
    {
12869
0
        g.NavId = 0;
12870
0
        SetNavFocusScope(window->NavRootFocusScopeId);
12871
0
        return;
12872
0
    }
12873
12874
79
    bool init_for_nav = false;
12875
79
    if (window == window->RootWindow || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit)
12876
76
        init_for_nav = true;
12877
79
    IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from NavInitWindow(), init_for_nav=%d, window=\"%s\", layer=%d\n", init_for_nav, window->Name, g.NavLayer);
12878
79
    if (init_for_nav)
12879
76
    {
12880
76
        SetNavID(0, g.NavLayer, window->NavRootFocusScopeId, ImRect());
12881
76
        g.NavInitRequest = true;
12882
76
        g.NavInitRequestFromMove = false;
12883
76
        g.NavInitResult.ID = 0;
12884
76
        NavUpdateAnyRequestFlag();
12885
76
    }
12886
3
    else
12887
3
    {
12888
3
        g.NavId = window->NavLastIds[0];
12889
3
        SetNavFocusScope(window->NavRootFocusScopeId);
12890
3
    }
12891
79
}
12892
12893
static ImVec2 ImGui::NavCalcPreferredRefPos()
12894
0
{
12895
0
    ImGuiContext& g = *GImGui;
12896
0
    ImGuiWindow* window = g.NavWindow;
12897
0
    const bool activated_shortcut = g.ActiveId != 0 && g.ActiveIdFromShortcut && g.ActiveId == g.LastItemData.ID;
12898
12899
    // Testing for !activated_shortcut here could in theory be removed if we decided that activating a remote shortcut altered one of the g.NavDisableXXX flag.
12900
0
    if ((g.NavDisableHighlight || !g.NavDisableMouseHover || !window) && !activated_shortcut)
12901
0
    {
12902
        // Mouse (we need a fallback in case the mouse becomes invalid after being used)
12903
        // The +1.0f offset when stored by OpenPopupEx() allows reopening this or another popup (same or another mouse button) while not moving the mouse, it is pretty standard.
12904
        // In theory we could move that +1.0f offset in OpenPopupEx()
12905
0
        ImVec2 p = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : g.MouseLastValidPos;
12906
0
        return ImVec2(p.x + 1.0f, p.y);
12907
0
    }
12908
0
    else
12909
0
    {
12910
        // When navigation is active and mouse is disabled, pick a position around the bottom left of the currently navigated item
12911
0
        ImRect ref_rect;
12912
0
        if (activated_shortcut)
12913
0
            ref_rect = g.LastItemData.NavRect;
12914
0
        else
12915
0
            ref_rect = WindowRectRelToAbs(window, window->NavRectRel[g.NavLayer]);
12916
12917
        // Take account of upcoming scrolling (maybe set mouse pos should be done in EndFrame?)
12918
0
        if (window->LastFrameActive != g.FrameCount && (window->ScrollTarget.x != FLT_MAX || window->ScrollTarget.y != FLT_MAX))
12919
0
        {
12920
0
            ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
12921
0
            ref_rect.Translate(window->Scroll - next_scroll);
12922
0
        }
12923
0
        ImVec2 pos = ImVec2(ref_rect.Min.x + ImMin(g.Style.FramePadding.x * 4, ref_rect.GetWidth()), ref_rect.Max.y - ImMin(g.Style.FramePadding.y, ref_rect.GetHeight()));
12924
0
        ImGuiViewport* viewport = window->Viewport;
12925
0
        return ImTrunc(ImClamp(pos, viewport->Pos, viewport->Pos + viewport->Size)); // ImTrunc() is important because non-integer mouse position application in backend might be lossy and result in undesirable non-zero delta.
12926
0
    }
12927
0
}
12928
12929
float ImGui::GetNavTweakPressedAmount(ImGuiAxis axis)
12930
0
{
12931
0
    ImGuiContext& g = *GImGui;
12932
0
    float repeat_delay, repeat_rate;
12933
0
    GetTypematicRepeatRate(ImGuiInputFlags_RepeatRateNavTweak, &repeat_delay, &repeat_rate);
12934
12935
0
    ImGuiKey key_less, key_more;
12936
0
    if (g.NavInputSource == ImGuiInputSource_Gamepad)
12937
0
    {
12938
0
        key_less = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadLeft : ImGuiKey_GamepadDpadUp;
12939
0
        key_more = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadRight : ImGuiKey_GamepadDpadDown;
12940
0
    }
12941
0
    else
12942
0
    {
12943
0
        key_less = (axis == ImGuiAxis_X) ? ImGuiKey_LeftArrow : ImGuiKey_UpArrow;
12944
0
        key_more = (axis == ImGuiAxis_X) ? ImGuiKey_RightArrow : ImGuiKey_DownArrow;
12945
0
    }
12946
0
    float amount = (float)GetKeyPressedAmount(key_more, repeat_delay, repeat_rate) - (float)GetKeyPressedAmount(key_less, repeat_delay, repeat_rate);
12947
0
    if (amount != 0.0f && IsKeyDown(key_less) && IsKeyDown(key_more)) // Cancel when opposite directions are held, regardless of repeat phase
12948
0
        amount = 0.0f;
12949
0
    return amount;
12950
0
}
12951
12952
static void ImGui::NavUpdate()
12953
84.9k
{
12954
84.9k
    ImGuiContext& g = *GImGui;
12955
84.9k
    ImGuiIO& io = g.IO;
12956
12957
84.9k
    io.WantSetMousePos = false;
12958
    //if (g.NavScoringDebugCount > 0) IMGUI_DEBUG_LOG_NAV("[nav] NavScoringDebugCount %d for '%s' layer %d (Init:%d, Move:%d)\n", g.NavScoringDebugCount, g.NavWindow ? g.NavWindow->Name : "NULL", g.NavLayer, g.NavInitRequest || g.NavInitResultId != 0, g.NavMoveRequest);
12959
12960
    // Set input source based on which keys are last pressed (as some features differs when used with Gamepad vs Keyboard)
12961
    // FIXME-NAV: Now that keys are separated maybe we can get rid of NavInputSource?
12962
84.9k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12963
84.9k
    const ImGuiKey nav_gamepad_keys_to_change_source[] = { ImGuiKey_GamepadFaceRight, ImGuiKey_GamepadFaceLeft, ImGuiKey_GamepadFaceUp, ImGuiKey_GamepadFaceDown, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown };
12964
84.9k
    if (nav_gamepad_active)
12965
0
        for (ImGuiKey key : nav_gamepad_keys_to_change_source)
12966
0
            if (IsKeyDown(key))
12967
0
                g.NavInputSource = ImGuiInputSource_Gamepad;
12968
84.9k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12969
84.9k
    const ImGuiKey nav_keyboard_keys_to_change_source[] = { ImGuiKey_Space, ImGuiKey_Enter, ImGuiKey_Escape, ImGuiKey_RightArrow, ImGuiKey_LeftArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow };
12970
84.9k
    if (nav_keyboard_active)
12971
84.9k
        for (ImGuiKey key : nav_keyboard_keys_to_change_source)
12972
594k
            if (IsKeyDown(key))
12973
31.5k
                g.NavInputSource = ImGuiInputSource_Keyboard;
12974
12975
    // Process navigation init request (select first/default focus)
12976
84.9k
    g.NavJustMovedToId = 0;
12977
84.9k
    g.NavJustMovedToFocusScopeId = g.NavJustMovedFromFocusScopeId = 0;
12978
84.9k
    if (g.NavInitResult.ID != 0)
12979
58
        NavInitRequestApplyResult();
12980
84.9k
    g.NavInitRequest = false;
12981
84.9k
    g.NavInitRequestFromMove = false;
12982
84.9k
    g.NavInitResult.ID = 0;
12983
12984
    // Process navigation move request
12985
84.9k
    if (g.NavMoveSubmitted)
12986
621
        NavMoveRequestApplyResult();
12987
84.9k
    g.NavTabbingCounter = 0;
12988
84.9k
    g.NavMoveSubmitted = g.NavMoveScoringItems = false;
12989
12990
    // Schedule mouse position update (will be done at the bottom of this function, after 1) processing all move requests and 2) updating scrolling)
12991
84.9k
    bool set_mouse_pos = false;
12992
84.9k
    if (g.NavMousePosDirty && g.NavIdIsAlive)
12993
327
        if (!g.NavDisableHighlight && g.NavDisableMouseHover && g.NavWindow)
12994
327
            set_mouse_pos = true;
12995
84.9k
    g.NavMousePosDirty = false;
12996
84.9k
    IM_ASSERT(g.NavLayer == ImGuiNavLayer_Main || g.NavLayer == ImGuiNavLayer_Menu);
12997
12998
    // Store our return window (for returning from Menu Layer to Main Layer) and clear it as soon as we step back in our own Layer 0
12999
84.9k
    if (g.NavWindow)
13000
13.5k
        NavSaveLastChildNavWindowIntoParent(g.NavWindow);
13001
84.9k
    if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == ImGuiNavLayer_Main)
13002
260
        g.NavWindow->NavLastChildNavWindow = NULL;
13003
13004
    // Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.)
13005
84.9k
    NavUpdateWindowing();
13006
13007
    // Set output flags for user application
13008
84.9k
    io.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);
13009
84.9k
    io.NavVisible = (io.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL);
13010
13011
    // Process NavCancel input (to close a popup, get back to parent, clear focus)
13012
84.9k
    NavUpdateCancelRequest();
13013
13014
    // Process manual activation request
13015
84.9k
    g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = 0;
13016
84.9k
    g.NavActivateFlags = ImGuiActivateFlags_None;
13017
84.9k
    if (g.NavId != 0 && !g.NavDisableHighlight && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
13018
2.98k
    {
13019
2.98k
        const bool activate_down = (nav_keyboard_active && IsKeyDown(ImGuiKey_Space, ImGuiKeyOwner_NoOwner)) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadActivate, ImGuiKeyOwner_NoOwner));
13020
2.98k
        const bool activate_pressed = activate_down && ((nav_keyboard_active && IsKeyPressed(ImGuiKey_Space, 0, ImGuiKeyOwner_NoOwner)) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadActivate, 0, ImGuiKeyOwner_NoOwner)));
13021
2.98k
        const bool input_down = (nav_keyboard_active && (IsKeyDown(ImGuiKey_Enter, ImGuiKeyOwner_NoOwner) || IsKeyDown(ImGuiKey_KeypadEnter, ImGuiKeyOwner_NoOwner))) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadInput, ImGuiKeyOwner_NoOwner));
13022
2.98k
        const bool input_pressed = input_down && ((nav_keyboard_active && (IsKeyPressed(ImGuiKey_Enter, 0, ImGuiKeyOwner_NoOwner) || IsKeyPressed(ImGuiKey_KeypadEnter, 0, ImGuiKeyOwner_NoOwner))) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadInput, 0, ImGuiKeyOwner_NoOwner)));
13023
2.98k
        if (g.ActiveId == 0 && activate_pressed)
13024
12
        {
13025
12
            g.NavActivateId = g.NavId;
13026
12
            g.NavActivateFlags = ImGuiActivateFlags_PreferTweak;
13027
12
        }
13028
2.98k
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && input_pressed)
13029
17
        {
13030
17
            g.NavActivateId = g.NavId;
13031
17
            g.NavActivateFlags = ImGuiActivateFlags_PreferInput;
13032
17
        }
13033
2.98k
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_down || input_down))
13034
101
            g.NavActivateDownId = g.NavId;
13035
2.98k
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_pressed || input_pressed))
13036
29
        {
13037
29
            g.NavActivatePressedId = g.NavId;
13038
29
            NavHighlightActivated(g.NavId);
13039
29
        }
13040
2.98k
    }
13041
84.9k
    if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
13042
0
        g.NavDisableHighlight = true;
13043
84.9k
    if (g.NavActivateId != 0)
13044
84.9k
        IM_ASSERT(g.NavActivateDownId == g.NavActivateId);
13045
13046
    // Highlight
13047
84.9k
    if (g.NavHighlightActivatedTimer > 0.0f)
13048
191
        g.NavHighlightActivatedTimer = ImMax(0.0f, g.NavHighlightActivatedTimer - io.DeltaTime);
13049
84.9k
    if (g.NavHighlightActivatedTimer == 0.0f)
13050
84.8k
        g.NavHighlightActivatedId = 0;
13051
13052
    // Process programmatic activation request
13053
    // FIXME-NAV: Those should eventually be queued (unlike focus they don't cancel each others)
13054
84.9k
    if (g.NavNextActivateId != 0)
13055
0
    {
13056
0
        g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavNextActivateId;
13057
0
        g.NavActivateFlags = g.NavNextActivateFlags;
13058
0
    }
13059
84.9k
    g.NavNextActivateId = 0;
13060
13061
    // Process move requests
13062
84.9k
    NavUpdateCreateMoveRequest();
13063
84.9k
    if (g.NavMoveDir == ImGuiDir_None)
13064
84.2k
        NavUpdateCreateTabbingRequest();
13065
84.9k
    NavUpdateAnyRequestFlag();
13066
84.9k
    g.NavIdIsAlive = false;
13067
13068
    // Scrolling
13069
84.9k
    if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget)
13070
13.5k
    {
13071
        // *Fallback* manual-scroll with Nav directional keys when window has no navigable item
13072
13.5k
        ImGuiWindow* window = g.NavWindow;
13073
13.5k
        const float scroll_speed = IM_ROUND(window->CalcFontSize() * 100 * io.DeltaTime); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported.
13074
13.5k
        const ImGuiDir move_dir = g.NavMoveDir;
13075
13.5k
        if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavWindowHasScrollY && move_dir != ImGuiDir_None)
13076
422
        {
13077
422
            if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
13078
150
                SetScrollX(window, ImTrunc(window->Scroll.x + ((move_dir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed));
13079
422
            if (move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down)
13080
272
                SetScrollY(window, ImTrunc(window->Scroll.y + ((move_dir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed));
13081
422
        }
13082
13083
        // *Normal* Manual scroll with LStick
13084
        // Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds.
13085
13.5k
        if (nav_gamepad_active)
13086
0
        {
13087
0
            const ImVec2 scroll_dir = GetKeyMagnitude2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
13088
0
            const float tweak_factor = IsKeyDown(ImGuiKey_NavGamepadTweakSlow) ? 1.0f / 10.0f : IsKeyDown(ImGuiKey_NavGamepadTweakFast) ? 10.0f : 1.0f;
13089
0
            if (scroll_dir.x != 0.0f && window->ScrollbarX)
13090
0
                SetScrollX(window, ImTrunc(window->Scroll.x + scroll_dir.x * scroll_speed * tweak_factor));
13091
0
            if (scroll_dir.y != 0.0f)
13092
0
                SetScrollY(window, ImTrunc(window->Scroll.y + scroll_dir.y * scroll_speed * tweak_factor));
13093
0
        }
13094
13.5k
    }
13095
13096
    // Always prioritize mouse highlight if navigation is disabled
13097
84.9k
    if (!nav_keyboard_active && !nav_gamepad_active)
13098
0
    {
13099
0
        g.NavDisableHighlight = true;
13100
0
        g.NavDisableMouseHover = set_mouse_pos = false;
13101
0
    }
13102
13103
    // Update mouse position if requested
13104
    // (This will take into account the possibility that a Scroll was queued in the window to offset our absolute mouse position before scroll has been applied)
13105
84.9k
    if (set_mouse_pos && (io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) && (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos))
13106
0
        TeleportMousePos(NavCalcPreferredRefPos());
13107
13108
    // [DEBUG]
13109
84.9k
    g.NavScoringDebugCount = 0;
13110
#if IMGUI_DEBUG_NAV_RECTS
13111
    if (ImGuiWindow* debug_window = g.NavWindow)
13112
    {
13113
        ImDrawList* draw_list = GetForegroundDrawList(debug_window);
13114
        int layer = g.NavLayer; /* for (int layer = 0; layer < 2; layer++)*/ { ImRect r = WindowRectRelToAbs(debug_window, debug_window->NavRectRel[layer]); draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 200, 0, 255)); }
13115
        //if (1) { ImU32 col = (!debug_window->Hidden) ? IM_COL32(255,0,255,255) : IM_COL32(255,0,0,255); ImVec2 p = NavCalcPreferredRefPos(); char buf[32]; ImFormatString(buf, 32, "%d", g.NavLayer); draw_list->AddCircleFilled(p, 3.0f, col); draw_list->AddText(NULL, 13.0f, p + ImVec2(8,-4), col, buf); }
13116
    }
13117
#endif
13118
84.9k
}
13119
13120
void ImGui::NavInitRequestApplyResult()
13121
58
{
13122
    // In very rare cases g.NavWindow may be null (e.g. clearing focus after requesting an init request, which does happen when releasing Alt while clicking on void)
13123
58
    ImGuiContext& g = *GImGui;
13124
58
    if (!g.NavWindow)
13125
7
        return;
13126
13127
51
    ImGuiNavItemData* result = &g.NavInitResult;
13128
51
    if (g.NavId != result->ID)
13129
50
    {
13130
50
        g.NavJustMovedFromFocusScopeId = g.NavFocusScopeId;
13131
50
        g.NavJustMovedToId = result->ID;
13132
50
        g.NavJustMovedToFocusScopeId = result->FocusScopeId;
13133
50
        g.NavJustMovedToKeyMods = 0;
13134
50
        g.NavJustMovedToIsTabbing = false;
13135
50
        g.NavJustMovedToHasSelectionData = (result->InFlags & ImGuiItemFlags_HasSelectionUserData) != 0;
13136
50
    }
13137
13138
    // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
13139
    // FIXME-NAV: On _NavFlattened windows, g.NavWindow will only be updated during subsequent frame. Not a problem currently.
13140
51
    IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: ApplyResult: NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
13141
51
    SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
13142
51
    g.NavIdIsAlive = true; // Mark as alive from previous frame as we got a result
13143
51
    if (result->SelectionUserData != ImGuiSelectionUserData_Invalid)
13144
0
        g.NavLastValidSelectionUserData = result->SelectionUserData;
13145
51
    if (g.NavInitRequestFromMove)
13146
16
        NavRestoreHighlightAfterMove();
13147
51
}
13148
13149
// Bias scoring rect ahead of scoring + update preferred pos (if missing) using source position
13150
static void NavBiasScoringRect(ImRect& r, ImVec2& preferred_pos_rel, ImGuiDir move_dir, ImGuiNavMoveFlags move_flags)
13151
752
{
13152
    // Bias initial rect
13153
752
    ImGuiContext& g = *GImGui;
13154
752
    const ImVec2 rel_to_abs_offset = g.NavWindow->DC.CursorStartPos;
13155
13156
    // Initialize bias on departure if we don't have any. So mouse-click + arrow will record bias.
13157
    // - We default to L/U bias, so moving down from a large source item into several columns will land on left-most column.
13158
    // - But each successful move sets new bias on one axis, only cleared when using mouse.
13159
752
    if ((move_flags & ImGuiNavMoveFlags_Forwarded) == 0)
13160
752
    {
13161
752
        if (preferred_pos_rel.x == FLT_MAX)
13162
310
            preferred_pos_rel.x = ImMin(r.Min.x + 1.0f, r.Max.x) - rel_to_abs_offset.x;
13163
752
        if (preferred_pos_rel.y == FLT_MAX)
13164
482
            preferred_pos_rel.y = r.GetCenter().y - rel_to_abs_offset.y;
13165
752
    }
13166
13167
    // Apply general bias on the other axis
13168
752
    if ((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) && preferred_pos_rel.x != FLT_MAX)
13169
478
        r.Min.x = r.Max.x = preferred_pos_rel.x + rel_to_abs_offset.x;
13170
274
    else if ((move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right) && preferred_pos_rel.y != FLT_MAX)
13171
274
        r.Min.y = r.Max.y = preferred_pos_rel.y + rel_to_abs_offset.y;
13172
752
}
13173
13174
void ImGui::NavUpdateCreateMoveRequest()
13175
84.9k
{
13176
84.9k
    ImGuiContext& g = *GImGui;
13177
84.9k
    ImGuiIO& io = g.IO;
13178
84.9k
    ImGuiWindow* window = g.NavWindow;
13179
84.9k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
13180
84.9k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
13181
13182
84.9k
    if (g.NavMoveForwardToNextFrame && window != NULL)
13183
0
    {
13184
        // Forwarding previous request (which has been modified, e.g. wrap around menus rewrite the requests with a starting rectangle at the other side of the window)
13185
        // (preserve most state, which were already set by the NavMoveRequestForward() function)
13186
0
        IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None);
13187
0
        IM_ASSERT(g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded);
13188
0
        IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestForward %d\n", g.NavMoveDir);
13189
0
    }
13190
84.9k
    else
13191
84.9k
    {
13192
        // Initiate directional inputs request
13193
84.9k
        g.NavMoveDir = ImGuiDir_None;
13194
84.9k
        g.NavMoveFlags = ImGuiNavMoveFlags_None;
13195
84.9k
        g.NavMoveScrollFlags = ImGuiScrollFlags_None;
13196
84.9k
        if (window && !g.NavWindowingTarget && !(window->Flags & ImGuiWindowFlags_NoNavInputs))
13197
13.5k
        {
13198
13.5k
            const ImGuiInputFlags repeat_mode = ImGuiInputFlags_Repeat | (ImGuiInputFlags)ImGuiInputFlags_RepeatRateNavMove;
13199
13.5k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Left)  && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadLeft,  repeat_mode, ImGuiKeyOwner_NoOwner)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_LeftArrow,  repeat_mode, ImGuiKeyOwner_NoOwner)))) { g.NavMoveDir = ImGuiDir_Left; }
13200
13.5k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Right) && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadRight, repeat_mode, ImGuiKeyOwner_NoOwner)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_RightArrow, repeat_mode, ImGuiKeyOwner_NoOwner)))) { g.NavMoveDir = ImGuiDir_Right; }
13201
13.5k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Up)    && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadUp,    repeat_mode, ImGuiKeyOwner_NoOwner)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_UpArrow,    repeat_mode, ImGuiKeyOwner_NoOwner)))) { g.NavMoveDir = ImGuiDir_Up; }
13202
13.5k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Down)  && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadDown,  repeat_mode, ImGuiKeyOwner_NoOwner)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_DownArrow,  repeat_mode, ImGuiKeyOwner_NoOwner)))) { g.NavMoveDir = ImGuiDir_Down; }
13203
13.5k
        }
13204
84.9k
        g.NavMoveClipDir = g.NavMoveDir;
13205
84.9k
        g.NavScoringNoClipRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);
13206
84.9k
    }
13207
13208
    // Update PageUp/PageDown/Home/End scroll
13209
    // FIXME-NAV: Consider enabling those keys even without the master ImGuiConfigFlags_NavEnableKeyboard flag?
13210
84.9k
    float scoring_rect_offset_y = 0.0f;
13211
84.9k
    if (window && g.NavMoveDir == ImGuiDir_None && nav_keyboard_active)
13212
12.9k
        scoring_rect_offset_y = NavUpdatePageUpPageDown();
13213
84.9k
    if (scoring_rect_offset_y != 0.0f)
13214
112
    {
13215
112
        g.NavScoringNoClipRect = window->InnerRect;
13216
112
        g.NavScoringNoClipRect.TranslateY(scoring_rect_offset_y);
13217
112
    }
13218
13219
    // [DEBUG] Always send a request when holding CTRL. Hold CTRL + Arrow change the direction.
13220
#if IMGUI_DEBUG_NAV_SCORING
13221
    //if (io.KeyCtrl && IsKeyPressed(ImGuiKey_C))
13222
    //    g.NavMoveDirForDebug = (ImGuiDir)((g.NavMoveDirForDebug + 1) & 3);
13223
    if (io.KeyCtrl)
13224
    {
13225
        if (g.NavMoveDir == ImGuiDir_None)
13226
            g.NavMoveDir = g.NavMoveDirForDebug;
13227
        g.NavMoveClipDir = g.NavMoveDir;
13228
        g.NavMoveFlags |= ImGuiNavMoveFlags_DebugNoResult;
13229
    }
13230
#endif
13231
13232
    // Submit
13233
84.9k
    g.NavMoveForwardToNextFrame = false;
13234
84.9k
    if (g.NavMoveDir != ImGuiDir_None)
13235
752
        NavMoveRequestSubmit(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags);
13236
13237
    // Moving with no reference triggers an init request (will be used as a fallback if the direction fails to find a match)
13238
84.9k
    if (g.NavMoveSubmitted && g.NavId == 0)
13239
562
    {
13240
562
        IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", window ? window->Name : "<NULL>", g.NavLayer);
13241
562
        g.NavInitRequest = g.NavInitRequestFromMove = true;
13242
562
        g.NavInitResult.ID = 0;
13243
562
        g.NavDisableHighlight = false;
13244
562
    }
13245
13246
    // When using gamepad, we project the reference nav bounding box into window visible area.
13247
    // This is to allow resuming navigation inside the visible area after doing a large amount of scrolling,
13248
    // since with gamepad all movements are relative (can't focus a visible object like we can with the mouse).
13249
84.9k
    if (g.NavMoveSubmitted && g.NavInputSource == ImGuiInputSource_Gamepad && g.NavLayer == ImGuiNavLayer_Main && window != NULL)// && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded))
13250
0
    {
13251
0
        bool clamp_x = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopX | ImGuiNavMoveFlags_WrapX)) == 0;
13252
0
        bool clamp_y = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopY | ImGuiNavMoveFlags_WrapY)) == 0;
13253
0
        ImRect inner_rect_rel = WindowRectAbsToRel(window, ImRect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1)));
13254
13255
        // Take account of changing scroll to handle triggering a new move request on a scrolling frame. (#6171)
13256
        // Otherwise 'inner_rect_rel' would be off on the move result frame.
13257
0
        inner_rect_rel.Translate(CalcNextScrollFromScrollTargetAndClamp(window) - window->Scroll);
13258
13259
0
        if ((clamp_x || clamp_y) && !inner_rect_rel.Contains(window->NavRectRel[g.NavLayer]))
13260
0
        {
13261
0
            IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel for gamepad move\n");
13262
0
            float pad_x = ImMin(inner_rect_rel.GetWidth(), window->CalcFontSize() * 0.5f);
13263
0
            float pad_y = ImMin(inner_rect_rel.GetHeight(), window->CalcFontSize() * 0.5f); // Terrible approximation for the intent of starting navigation from first fully visible item
13264
0
            inner_rect_rel.Min.x = clamp_x ? (inner_rect_rel.Min.x + pad_x) : -FLT_MAX;
13265
0
            inner_rect_rel.Max.x = clamp_x ? (inner_rect_rel.Max.x - pad_x) : +FLT_MAX;
13266
0
            inner_rect_rel.Min.y = clamp_y ? (inner_rect_rel.Min.y + pad_y) : -FLT_MAX;
13267
0
            inner_rect_rel.Max.y = clamp_y ? (inner_rect_rel.Max.y - pad_y) : +FLT_MAX;
13268
0
            window->NavRectRel[g.NavLayer].ClipWithFull(inner_rect_rel);
13269
0
            g.NavId = 0;
13270
0
        }
13271
0
    }
13272
13273
    // For scoring we use a single segment on the left side our current item bounding box (not touching the edge to avoid box overlap with zero-spaced items)
13274
84.9k
    ImRect scoring_rect;
13275
84.9k
    if (window != NULL)
13276
13.5k
    {
13277
13.5k
        ImRect nav_rect_rel = !window->NavRectRel[g.NavLayer].IsInverted() ? window->NavRectRel[g.NavLayer] : ImRect(0, 0, 0, 0);
13278
13.5k
        scoring_rect = WindowRectRelToAbs(window, nav_rect_rel);
13279
13.5k
        scoring_rect.TranslateY(scoring_rect_offset_y);
13280
13.5k
        if (g.NavMoveSubmitted)
13281
752
            NavBiasScoringRect(scoring_rect, window->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer], g.NavMoveDir, g.NavMoveFlags);
13282
13.5k
        IM_ASSERT(!scoring_rect.IsInverted()); // Ensure we have a non-inverted bounding box here will allow us to remove extraneous ImFabs() calls in NavScoreItem().
13283
        //GetForegroundDrawList()->AddRect(scoring_rect.Min, scoring_rect.Max, IM_COL32(255,200,0,255)); // [DEBUG]
13284
        //if (!g.NavScoringNoClipRect.IsInverted()) { GetForegroundDrawList()->AddRect(g.NavScoringNoClipRect.Min, g.NavScoringNoClipRect.Max, IM_COL32(255, 200, 0, 255)); } // [DEBUG]
13285
13.5k
    }
13286
84.9k
    g.NavScoringRect = scoring_rect;
13287
84.9k
    g.NavScoringNoClipRect.Add(scoring_rect);
13288
84.9k
}
13289
13290
void ImGui::NavUpdateCreateTabbingRequest()
13291
84.2k
{
13292
84.2k
    ImGuiContext& g = *GImGui;
13293
84.2k
    ImGuiWindow* window = g.NavWindow;
13294
84.2k
    IM_ASSERT(g.NavMoveDir == ImGuiDir_None);
13295
84.2k
    if (window == NULL || g.NavWindowingTarget != NULL || (window->Flags & ImGuiWindowFlags_NoNavInputs))
13296
71.4k
        return;
13297
13298
12.7k
    const bool tab_pressed = IsKeyPressed(ImGuiKey_Tab, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner) && !g.IO.KeyCtrl && !g.IO.KeyAlt;
13299
12.7k
    if (!tab_pressed)
13300
12.7k
        return;
13301
13302
    // Initiate tabbing request
13303
    // (this is ALWAYS ENABLED, regardless of ImGuiConfigFlags_NavEnableKeyboard flag!)
13304
    // See NavProcessItemForTabbingRequest() for a description of the various forward/backward tabbing cases with and without wrapping.
13305
75
    const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
13306
75
    if (nav_keyboard_active)
13307
75
        g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.NavDisableHighlight == true && g.ActiveId == 0) ? 0 : +1;
13308
0
    else
13309
0
        g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.ActiveId == 0) ? 0 : +1;
13310
75
    ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_Activate;
13311
75
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
13312
75
    ImGuiDir clip_dir = (g.NavTabbingDir < 0) ? ImGuiDir_Up : ImGuiDir_Down;
13313
75
    NavMoveRequestSubmit(ImGuiDir_None, clip_dir, move_flags, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
13314
75
    g.NavTabbingCounter = -1;
13315
75
}
13316
13317
// Apply result from previous frame navigation directional move request. Always called from NavUpdate()
13318
void ImGui::NavMoveRequestApplyResult()
13319
621
{
13320
621
    ImGuiContext& g = *GImGui;
13321
#if IMGUI_DEBUG_NAV_SCORING
13322
    if (g.NavMoveFlags & ImGuiNavMoveFlags_DebugNoResult) // [DEBUG] Scoring all items in NavWindow at all times
13323
        return;
13324
#endif
13325
13326
    // Select which result to use
13327
621
    ImGuiNavItemData* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : (g.NavMoveResultOther.ID != 0) ? &g.NavMoveResultOther : NULL;
13328
13329
    // Tabbing forward wrap
13330
621
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && result == NULL)
13331
38
        if ((g.NavTabbingCounter == 1 || g.NavTabbingDir == 0) && g.NavTabbingResultFirst.ID)
13332
12
            result = &g.NavTabbingResultFirst;
13333
13334
    // In a situation when there are no results but NavId != 0, re-enable the Navigation highlight (because g.NavId is not considered as a possible result)
13335
621
    const ImGuiAxis axis = (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;
13336
621
    if (result == NULL)
13337
579
    {
13338
579
        if (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing)
13339
26
            g.NavMoveFlags |= ImGuiNavMoveFlags_NoSetNavHighlight;
13340
579
        if (g.NavId != 0 && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavHighlight) == 0)
13341
125
            NavRestoreHighlightAfterMove();
13342
579
        NavClearPreferredPosForAxis(axis); // On a failed move, clear preferred pos for this axis.
13343
579
        IMGUI_DEBUG_LOG_NAV("[nav] NavMoveSubmitted but not led to a result!\n");
13344
579
        return;
13345
579
    }
13346
13347
    // PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page.
13348
42
    if (g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet)
13349
8
        if (g.NavMoveResultLocalVisible.ID != 0 && g.NavMoveResultLocalVisible.ID != g.NavId)
13350
0
            result = &g.NavMoveResultLocalVisible;
13351
13352
    // Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules.
13353
42
    if (result != &g.NavMoveResultOther && g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow)
13354
0
        if ((g.NavMoveResultOther.DistBox < result->DistBox) || (g.NavMoveResultOther.DistBox == result->DistBox && g.NavMoveResultOther.DistCenter < result->DistCenter))
13355
0
            result = &g.NavMoveResultOther;
13356
42
    IM_ASSERT(g.NavWindow && result->Window);
13357
13358
    // Scroll to keep newly navigated item fully into view.
13359
42
    if (g.NavLayer == ImGuiNavLayer_Main)
13360
42
    {
13361
42
        ImRect rect_abs = WindowRectRelToAbs(result->Window, result->RectRel);
13362
42
        ScrollToRectEx(result->Window, rect_abs, g.NavMoveScrollFlags);
13363
13364
42
        if (g.NavMoveFlags & ImGuiNavMoveFlags_ScrollToEdgeY)
13365
9
        {
13366
            // FIXME: Should remove this? Or make more precise: use ScrollToRectEx() with edge?
13367
9
            float scroll_target = (g.NavMoveDir == ImGuiDir_Up) ? result->Window->ScrollMax.y : 0.0f;
13368
9
            SetScrollY(result->Window, scroll_target);
13369
9
        }
13370
42
    }
13371
13372
42
    if (g.NavWindow != result->Window)
13373
0
    {
13374
0
        IMGUI_DEBUG_LOG_FOCUS("[focus] NavMoveRequest: SetNavWindow(\"%s\")\n", result->Window->Name);
13375
0
        g.NavWindow = result->Window;
13376
0
        g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
13377
0
    }
13378
13379
    // Clear active id unless requested not to
13380
    // FIXME: ImGuiNavMoveFlags_NoClearActiveId is currently unused as we don't have a clear strategy to preserve active id after interaction,
13381
    // so this is mostly provided as a gateway for further experiments (see #1418, #2890)
13382
42
    if (g.ActiveId != result->ID && (g.NavMoveFlags & ImGuiNavMoveFlags_NoClearActiveId) == 0)
13383
42
        ClearActiveID();
13384
13385
    // Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId)
13386
    // PageUp/PageDown however sets always set NavJustMovedTo (vs Home/End which doesn't) mimicking Windows behavior.
13387
42
    if ((g.NavId != result->ID || (g.NavMoveFlags & ImGuiNavMoveFlags_IsPageMove)) && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSelect) == 0)
13388
8
    {
13389
8
        g.NavJustMovedFromFocusScopeId = g.NavFocusScopeId;
13390
8
        g.NavJustMovedToId = result->ID;
13391
8
        g.NavJustMovedToFocusScopeId = result->FocusScopeId;
13392
8
        g.NavJustMovedToKeyMods = g.NavMoveKeyMods;
13393
8
        g.NavJustMovedToIsTabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) != 0;
13394
8
        g.NavJustMovedToHasSelectionData = (result->InFlags & ImGuiItemFlags_HasSelectionUserData) != 0;
13395
        //IMGUI_DEBUG_LOG_NAV("[nav] NavJustMovedFromFocusScopeId = 0x%08X, NavJustMovedToFocusScopeId = 0x%08X\n", g.NavJustMovedFromFocusScopeId, g.NavJustMovedToFocusScopeId);
13396
8
    }
13397
13398
    // Apply new NavID/Focus
13399
42
    IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
13400
42
    ImVec2 preferred_scoring_pos_rel = g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer];
13401
42
    SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
13402
42
    if (result->SelectionUserData != ImGuiSelectionUserData_Invalid)
13403
0
        g.NavLastValidSelectionUserData = result->SelectionUserData;
13404
13405
    // Restore last preferred position for current axis
13406
    // (storing in RootWindowForNav-> as the info is desirable at the beginning of a Move Request. In theory all storage should use RootWindowForNav..)
13407
42
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) == 0)
13408
30
    {
13409
30
        preferred_scoring_pos_rel[axis] = result->RectRel.GetCenter()[axis];
13410
30
        g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer] = preferred_scoring_pos_rel;
13411
30
    }
13412
13413
    // Tabbing: Activates Inputable, otherwise only Focus
13414
42
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && (result->InFlags & ImGuiItemFlags_Inputable) == 0)
13415
12
        g.NavMoveFlags &= ~ImGuiNavMoveFlags_Activate;
13416
13417
    // Activate
13418
42
    if (g.NavMoveFlags & ImGuiNavMoveFlags_Activate)
13419
0
    {
13420
0
        g.NavNextActivateId = result->ID;
13421
0
        g.NavNextActivateFlags = ImGuiActivateFlags_None;
13422
0
        if (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing)
13423
0
            g.NavNextActivateFlags |= ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_TryToPreserveState | ImGuiActivateFlags_FromTabbing;
13424
0
    }
13425
13426
    // Enable nav highlight
13427
42
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavHighlight) == 0)
13428
42
        NavRestoreHighlightAfterMove();
13429
42
}
13430
13431
// Process NavCancel input (to close a popup, get back to parent, clear focus)
13432
// FIXME: In order to support e.g. Escape to clear a selection we'll need:
13433
// - either to store the equivalent of ActiveIdUsingKeyInputMask for a FocusScope and test for it.
13434
// - either to move most/all of those tests to the epilogue/end functions of the scope they are dealing with (e.g. exit child window in EndChild()) or in EndFrame(), to allow an earlier intercept
13435
static void ImGui::NavUpdateCancelRequest()
13436
84.9k
{
13437
84.9k
    ImGuiContext& g = *GImGui;
13438
84.9k
    const bool nav_gamepad_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
13439
84.9k
    const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
13440
84.9k
    if (!(nav_keyboard_active && IsKeyPressed(ImGuiKey_Escape, 0, ImGuiKeyOwner_NoOwner)) && !(nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadCancel, 0, ImGuiKeyOwner_NoOwner)))
13441
83.3k
        return;
13442
13443
1.60k
    IMGUI_DEBUG_LOG_NAV("[nav] NavUpdateCancelRequest()\n");
13444
1.60k
    if (g.ActiveId != 0)
13445
0
    {
13446
0
        ClearActiveID();
13447
0
    }
13448
1.60k
    else if (g.NavLayer != ImGuiNavLayer_Main)
13449
0
    {
13450
        // Leave the "menu" layer
13451
0
        NavRestoreLayer(ImGuiNavLayer_Main);
13452
0
        NavRestoreHighlightAfterMove();
13453
0
    }
13454
1.60k
    else if (g.NavWindow && g.NavWindow != g.NavWindow->RootWindow && !(g.NavWindow->RootWindowForNav->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->RootWindowForNav->ParentWindow)
13455
339
    {
13456
        // Exit child window
13457
339
        ImGuiWindow* child_window = g.NavWindow->RootWindowForNav;
13458
339
        ImGuiWindow* parent_window = child_window->ParentWindow;
13459
339
        IM_ASSERT(child_window->ChildId != 0);
13460
339
        FocusWindow(parent_window);
13461
339
        SetNavID(child_window->ChildId, ImGuiNavLayer_Main, 0, WindowRectAbsToRel(parent_window, child_window->Rect()));
13462
339
        NavRestoreHighlightAfterMove();
13463
339
    }
13464
1.27k
    else if (g.OpenPopupStack.Size > 0 && g.OpenPopupStack.back().Window != NULL && !(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal))
13465
0
    {
13466
        // Close open popup/menu
13467
0
        ClosePopupToLevel(g.OpenPopupStack.Size - 1, true);
13468
0
    }
13469
1.27k
    else
13470
1.27k
    {
13471
        // Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
13472
1.27k
        if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup) || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
13473
75
            g.NavWindow->NavLastIds[0] = 0;
13474
1.27k
        g.NavId = 0;
13475
1.27k
    }
13476
1.60k
}
13477
13478
// Handle PageUp/PageDown/Home/End keys
13479
// Called from NavUpdateCreateMoveRequest() which will use our output to create a move request
13480
// FIXME-NAV: This doesn't work properly with NavFlattened siblings as we use NavWindow rectangle for reference
13481
// FIXME-NAV: how to get Home/End to aim at the beginning/end of a 2D grid?
13482
static float ImGui::NavUpdatePageUpPageDown()
13483
12.9k
{
13484
12.9k
    ImGuiContext& g = *GImGui;
13485
12.9k
    ImGuiWindow* window = g.NavWindow;
13486
12.9k
    if ((window->Flags & ImGuiWindowFlags_NoNavInputs) || g.NavWindowingTarget != NULL)
13487
0
        return 0.0f;
13488
13489
12.9k
    const bool page_up_held = IsKeyDown(ImGuiKey_PageUp, ImGuiKeyOwner_NoOwner);
13490
12.9k
    const bool page_down_held = IsKeyDown(ImGuiKey_PageDown, ImGuiKeyOwner_NoOwner);
13491
12.9k
    const bool home_pressed = IsKeyPressed(ImGuiKey_Home, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner);
13492
12.9k
    const bool end_pressed = IsKeyPressed(ImGuiKey_End, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner);
13493
12.9k
    if (page_up_held == page_down_held && home_pressed == end_pressed) // Proceed if either (not both) are pressed, otherwise early out
13494
11.9k
        return 0.0f;
13495
13496
1.06k
    if (g.NavLayer != ImGuiNavLayer_Main)
13497
0
        NavRestoreLayer(ImGuiNavLayer_Main);
13498
13499
1.06k
    if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavWindowHasScrollY)
13500
755
    {
13501
        // Fallback manual-scroll when window has no navigable item
13502
755
        if (IsKeyPressed(ImGuiKey_PageUp, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner))
13503
4
            SetScrollY(window, window->Scroll.y - window->InnerRect.GetHeight());
13504
751
        else if (IsKeyPressed(ImGuiKey_PageDown, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner))
13505
14
            SetScrollY(window, window->Scroll.y + window->InnerRect.GetHeight());
13506
737
        else if (home_pressed)
13507
4
            SetScrollY(window, 0.0f);
13508
733
        else if (end_pressed)
13509
39
            SetScrollY(window, window->ScrollMax.y);
13510
755
    }
13511
309
    else
13512
309
    {
13513
309
        ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer];
13514
309
        const float page_offset_y = ImMax(0.0f, window->InnerRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight());
13515
309
        float nav_scoring_rect_offset_y = 0.0f;
13516
309
        if (IsKeyPressed(ImGuiKey_PageUp, true))
13517
3
        {
13518
3
            nav_scoring_rect_offset_y = -page_offset_y;
13519
3
            g.NavMoveDir = ImGuiDir_Down; // Because our scoring rect is offset up, we request the down direction (so we can always land on the last item)
13520
3
            g.NavMoveClipDir = ImGuiDir_Up;
13521
3
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet | ImGuiNavMoveFlags_IsPageMove;
13522
3
        }
13523
306
        else if (IsKeyPressed(ImGuiKey_PageDown, true))
13524
109
        {
13525
109
            nav_scoring_rect_offset_y = +page_offset_y;
13526
109
            g.NavMoveDir = ImGuiDir_Up; // Because our scoring rect is offset down, we request the up direction (so we can always land on the last item)
13527
109
            g.NavMoveClipDir = ImGuiDir_Down;
13528
109
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet | ImGuiNavMoveFlags_IsPageMove;
13529
109
        }
13530
197
        else if (home_pressed)
13531
18
        {
13532
            // FIXME-NAV: handling of Home/End is assuming that the top/bottom most item will be visible with Scroll.y == 0/ScrollMax.y
13533
            // Scrolling will be handled via the ImGuiNavMoveFlags_ScrollToEdgeY flag, we don't scroll immediately to avoid scrolling happening before nav result.
13534
            // Preserve current horizontal position if we have any.
13535
18
            nav_rect_rel.Min.y = nav_rect_rel.Max.y = 0.0f;
13536
18
            if (nav_rect_rel.IsInverted())
13537
0
                nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
13538
18
            g.NavMoveDir = ImGuiDir_Down;
13539
18
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
13540
            // FIXME-NAV: MoveClipDir left to _None, intentional?
13541
18
        }
13542
179
        else if (end_pressed)
13543
49
        {
13544
49
            nav_rect_rel.Min.y = nav_rect_rel.Max.y = window->ContentSize.y;
13545
49
            if (nav_rect_rel.IsInverted())
13546
0
                nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
13547
49
            g.NavMoveDir = ImGuiDir_Up;
13548
49
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
13549
            // FIXME-NAV: MoveClipDir left to _None, intentional?
13550
49
        }
13551
309
        return nav_scoring_rect_offset_y;
13552
309
    }
13553
755
    return 0.0f;
13554
1.06k
}
13555
13556
static void ImGui::NavEndFrame()
13557
84.9k
{
13558
84.9k
    ImGuiContext& g = *GImGui;
13559
13560
    // Show CTRL+TAB list window
13561
84.9k
    if (g.NavWindowingTarget != NULL)
13562
0
        NavUpdateWindowingOverlay();
13563
13564
    // Perform wrap-around in menus
13565
    // FIXME-NAV: Wrap may need to apply a weight bias on the other axis. e.g. 4x4 grid with 2 last items missing on last item won't handle LoopY/WrapY correctly.
13566
    // FIXME-NAV: Wrap (not Loop) support could be handled by the scoring function and then WrapX would function without an extra frame.
13567
84.9k
    if (g.NavWindow && NavMoveRequestButNoResultYet() && (g.NavMoveFlags & ImGuiNavMoveFlags_WrapMask_) && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded) == 0)
13568
0
        NavUpdateCreateWrappingRequest();
13569
84.9k
}
13570
13571
static void ImGui::NavUpdateCreateWrappingRequest()
13572
0
{
13573
0
    ImGuiContext& g = *GImGui;
13574
0
    ImGuiWindow* window = g.NavWindow;
13575
13576
0
    bool do_forward = false;
13577
0
    ImRect bb_rel = window->NavRectRel[g.NavLayer];
13578
0
    ImGuiDir clip_dir = g.NavMoveDir;
13579
13580
0
    const ImGuiNavMoveFlags move_flags = g.NavMoveFlags;
13581
    //const ImGuiAxis move_axis = (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;
13582
0
    if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
13583
0
    {
13584
0
        bb_rel.Min.x = bb_rel.Max.x = window->ContentSize.x + window->WindowPadding.x;
13585
0
        if (move_flags & ImGuiNavMoveFlags_WrapX)
13586
0
        {
13587
0
            bb_rel.TranslateY(-bb_rel.GetHeight()); // Previous row
13588
0
            clip_dir = ImGuiDir_Up;
13589
0
        }
13590
0
        do_forward = true;
13591
0
    }
13592
0
    if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
13593
0
    {
13594
0
        bb_rel.Min.x = bb_rel.Max.x = -window->WindowPadding.x;
13595
0
        if (move_flags & ImGuiNavMoveFlags_WrapX)
13596
0
        {
13597
0
            bb_rel.TranslateY(+bb_rel.GetHeight()); // Next row
13598
0
            clip_dir = ImGuiDir_Down;
13599
0
        }
13600
0
        do_forward = true;
13601
0
    }
13602
0
    if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
13603
0
    {
13604
0
        bb_rel.Min.y = bb_rel.Max.y = window->ContentSize.y + window->WindowPadding.y;
13605
0
        if (move_flags & ImGuiNavMoveFlags_WrapY)
13606
0
        {
13607
0
            bb_rel.TranslateX(-bb_rel.GetWidth()); // Previous column
13608
0
            clip_dir = ImGuiDir_Left;
13609
0
        }
13610
0
        do_forward = true;
13611
0
    }
13612
0
    if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
13613
0
    {
13614
0
        bb_rel.Min.y = bb_rel.Max.y = -window->WindowPadding.y;
13615
0
        if (move_flags & ImGuiNavMoveFlags_WrapY)
13616
0
        {
13617
0
            bb_rel.TranslateX(+bb_rel.GetWidth()); // Next column
13618
0
            clip_dir = ImGuiDir_Right;
13619
0
        }
13620
0
        do_forward = true;
13621
0
    }
13622
0
    if (!do_forward)
13623
0
        return;
13624
0
    window->NavRectRel[g.NavLayer] = bb_rel;
13625
0
    NavClearPreferredPosForAxis(ImGuiAxis_X);
13626
0
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
13627
0
    NavMoveRequestForward(g.NavMoveDir, clip_dir, move_flags, g.NavMoveScrollFlags);
13628
0
}
13629
13630
static int ImGui::FindWindowFocusIndex(ImGuiWindow* window)
13631
0
{
13632
0
    ImGuiContext& g = *GImGui;
13633
0
    IM_UNUSED(g);
13634
0
    int order = window->FocusOrder;
13635
0
    IM_ASSERT(window->RootWindow == window); // No child window (not testing _ChildWindow because of docking)
13636
0
    IM_ASSERT(g.WindowsFocusOrder[order] == window);
13637
0
    return order;
13638
0
}
13639
13640
static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N)
13641
0
{
13642
0
    ImGuiContext& g = *GImGui;
13643
0
    for (int i = i_start; i >= 0 && i < g.WindowsFocusOrder.Size && i != i_stop; i += dir)
13644
0
        if (ImGui::IsWindowNavFocusable(g.WindowsFocusOrder[i]))
13645
0
            return g.WindowsFocusOrder[i];
13646
0
    return NULL;
13647
0
}
13648
13649
static void NavUpdateWindowingHighlightWindow(int focus_change_dir)
13650
0
{
13651
0
    ImGuiContext& g = *GImGui;
13652
0
    IM_ASSERT(g.NavWindowingTarget);
13653
0
    if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal)
13654
0
        return;
13655
13656
0
    const int i_current = ImGui::FindWindowFocusIndex(g.NavWindowingTarget);
13657
0
    ImGuiWindow* window_target = FindWindowNavFocusable(i_current + focus_change_dir, -INT_MAX, focus_change_dir);
13658
0
    if (!window_target)
13659
0
        window_target = FindWindowNavFocusable((focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_current, focus_change_dir);
13660
0
    if (window_target) // Don't reset windowing target if there's a single window in the list
13661
0
    {
13662
0
        g.NavWindowingTarget = g.NavWindowingTargetAnim = window_target;
13663
0
        g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
13664
0
    }
13665
0
    g.NavWindowingToggleLayer = false;
13666
0
}
13667
13668
// Windowing management mode
13669
// Keyboard: CTRL+Tab (change focus/move/resize), Alt (toggle menu layer)
13670
// Gamepad:  Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer)
13671
static void ImGui::NavUpdateWindowing()
13672
84.9k
{
13673
84.9k
    ImGuiContext& g = *GImGui;
13674
84.9k
    ImGuiIO& io = g.IO;
13675
13676
84.9k
    ImGuiWindow* apply_focus_window = NULL;
13677
84.9k
    bool apply_toggle_layer = false;
13678
13679
84.9k
    ImGuiWindow* modal_window = GetTopMostPopupModal();
13680
84.9k
    bool allow_windowing = (modal_window == NULL); // FIXME: This prevent CTRL+TAB from being usable with windows that are inside the Begin-stack of that modal.
13681
84.9k
    if (!allow_windowing)
13682
0
        g.NavWindowingTarget = NULL;
13683
13684
    // Fade out
13685
84.9k
    if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL)
13686
0
    {
13687
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha - io.DeltaTime * 10.0f, 0.0f);
13688
0
        if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
13689
0
            g.NavWindowingTargetAnim = NULL;
13690
0
    }
13691
13692
    // Start CTRL+Tab or Square+L/R window selection
13693
    // (g.ConfigNavWindowingKeyNext/g.ConfigNavWindowingKeyPrev defaults are ImGuiMod_Ctrl|ImGuiKey_Tab and ImGuiMod_Ctrl|ImGuiMod_Shift|ImGuiKey_Tab)
13694
84.9k
    const ImGuiID owner_id = ImHashStr("###NavUpdateWindowing");
13695
84.9k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
13696
84.9k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
13697
84.9k
    const bool keyboard_next_window = allow_windowing && g.ConfigNavWindowingKeyNext && Shortcut(g.ConfigNavWindowingKeyNext, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways, owner_id);
13698
84.9k
    const bool keyboard_prev_window = allow_windowing && g.ConfigNavWindowingKeyPrev && Shortcut(g.ConfigNavWindowingKeyPrev, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways, owner_id);
13699
84.9k
    const bool start_windowing_with_gamepad = allow_windowing && nav_gamepad_active && !g.NavWindowingTarget && IsKeyPressed(ImGuiKey_NavGamepadMenu, ImGuiInputFlags_None);
13700
84.9k
    const bool start_windowing_with_keyboard = allow_windowing && !g.NavWindowingTarget && (keyboard_next_window || keyboard_prev_window); // Note: enabled even without NavEnableKeyboard!
13701
84.9k
    if (start_windowing_with_gamepad || start_windowing_with_keyboard)
13702
0
        if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1))
13703
0
        {
13704
0
            g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow;
13705
0
            g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f;
13706
0
            g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
13707
0
            g.NavWindowingToggleLayer = start_windowing_with_gamepad ? true : false; // Gamepad starts toggling layer
13708
0
            g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_Keyboard : ImGuiInputSource_Gamepad;
13709
13710
            // Manually register ownership of our mods. Using a global route in the Shortcut() calls instead would probably be correct but may have more side-effects.
13711
0
            if (keyboard_next_window || keyboard_prev_window)
13712
0
                SetKeyOwnersForKeyChord((g.ConfigNavWindowingKeyNext | g.ConfigNavWindowingKeyPrev) & ImGuiMod_Mask_, owner_id);
13713
0
        }
13714
13715
    // Gamepad update
13716
84.9k
    g.NavWindowingTimer += io.DeltaTime;
13717
84.9k
    if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Gamepad)
13718
0
    {
13719
        // Highlight only appears after a brief time holding the button, so that a fast tap on PadMenu (to toggle NavLayer) doesn't add visual noise
13720
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f));
13721
13722
        // Select window to focus
13723
0
        const int focus_change_dir = (int)IsKeyPressed(ImGuiKey_GamepadL1) - (int)IsKeyPressed(ImGuiKey_GamepadR1);
13724
0
        if (focus_change_dir != 0)
13725
0
        {
13726
0
            NavUpdateWindowingHighlightWindow(focus_change_dir);
13727
0
            g.NavWindowingHighlightAlpha = 1.0f;
13728
0
        }
13729
13730
        // Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most)
13731
0
        if (!IsKeyDown(ImGuiKey_NavGamepadMenu))
13732
0
        {
13733
0
            g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore.
13734
0
            if (g.NavWindowingToggleLayer && g.NavWindow)
13735
0
                apply_toggle_layer = true;
13736
0
            else if (!g.NavWindowingToggleLayer)
13737
0
                apply_focus_window = g.NavWindowingTarget;
13738
0
            g.NavWindowingTarget = NULL;
13739
0
        }
13740
0
    }
13741
13742
    // Keyboard: Focus
13743
84.9k
    if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Keyboard)
13744
0
    {
13745
        // Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise
13746
0
        ImGuiKeyChord shared_mods = ((g.ConfigNavWindowingKeyNext ? g.ConfigNavWindowingKeyNext : ImGuiMod_Mask_) & (g.ConfigNavWindowingKeyPrev ? g.ConfigNavWindowingKeyPrev : ImGuiMod_Mask_)) & ImGuiMod_Mask_;
13747
0
        IM_ASSERT(shared_mods != 0); // Next/Prev shortcut currently needs a shared modifier to "hold", otherwise Prev actions would keep cycling between two windows.
13748
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f
13749
0
        if (keyboard_next_window || keyboard_prev_window)
13750
0
            NavUpdateWindowingHighlightWindow(keyboard_next_window ? -1 : +1);
13751
0
        else if ((io.KeyMods & shared_mods) != shared_mods)
13752
0
            apply_focus_window = g.NavWindowingTarget;
13753
0
    }
13754
13755
    // Keyboard: Press and Release ALT to toggle menu layer
13756
84.9k
    const ImGuiKey windowing_toggle_keys[] = { ImGuiKey_LeftAlt, ImGuiKey_RightAlt };
13757
84.9k
    for (ImGuiKey windowing_toggle_key : windowing_toggle_keys)
13758
169k
        if (nav_keyboard_active && IsKeyPressed(windowing_toggle_key, 0, ImGuiKeyOwner_NoOwner))
13759
628
        {
13760
628
            g.NavWindowingToggleLayer = true;
13761
628
            g.NavWindowingToggleKey = windowing_toggle_key;
13762
628
            g.NavInputSource = ImGuiInputSource_Keyboard;
13763
628
            break;
13764
628
        }
13765
84.9k
    if (g.NavWindowingToggleLayer && g.NavInputSource == ImGuiInputSource_Keyboard)
13766
3.80k
    {
13767
        // We cancel toggling nav layer when any text has been typed (generally while holding Alt). (See #370)
13768
        // We cancel toggling nav layer when other modifiers are pressed. (See #4439)
13769
        // - AltGR is Alt+Ctrl on some layout but we can't reliably detect it (not all backends/systems/layout emit it as Alt+Ctrl).
13770
        // We cancel toggling nav layer if an owner has claimed the key.
13771
3.80k
        if (io.InputQueueCharacters.Size > 0 || io.KeyCtrl || io.KeyShift || io.KeySuper)
13772
125
            g.NavWindowingToggleLayer = false;
13773
3.80k
        if (TestKeyOwner(g.NavWindowingToggleKey, ImGuiKeyOwner_NoOwner) == false || TestKeyOwner(ImGuiMod_Alt, ImGuiKeyOwner_NoOwner) == false)
13774
0
            g.NavWindowingToggleLayer = false;
13775
13776
        // Apply layer toggle on Alt release
13777
        // Important: as before version <18314 we lacked an explicit IO event for focus gain/loss, we also compare mouse validity to detect old backends clearing mouse pos on focus loss.
13778
3.80k
        if (IsKeyReleased(g.NavWindowingToggleKey) && g.NavWindowingToggleLayer)
13779
327
            if (g.ActiveId == 0 || g.ActiveIdAllowOverlap)
13780
327
                if (IsMousePosValid(&io.MousePos) == IsMousePosValid(&io.MousePosPrev))
13781
327
                    apply_toggle_layer = true;
13782
3.80k
        if (!IsKeyDown(g.NavWindowingToggleKey))
13783
612
            g.NavWindowingToggleLayer = false;
13784
3.80k
    }
13785
13786
    // Move window
13787
84.9k
    if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove))
13788
0
    {
13789
0
        ImVec2 nav_move_dir;
13790
0
        if (g.NavInputSource == ImGuiInputSource_Keyboard && !io.KeyShift)
13791
0
            nav_move_dir = GetKeyMagnitude2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
13792
0
        if (g.NavInputSource == ImGuiInputSource_Gamepad)
13793
0
            nav_move_dir = GetKeyMagnitude2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
13794
0
        if (nav_move_dir.x != 0.0f || nav_move_dir.y != 0.0f)
13795
0
        {
13796
0
            const float NAV_MOVE_SPEED = 800.0f;
13797
0
            const float move_step = NAV_MOVE_SPEED * io.DeltaTime * ImMin(io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y);
13798
0
            g.NavWindowingAccumDeltaPos += nav_move_dir * move_step;
13799
0
            g.NavDisableMouseHover = true;
13800
0
            ImVec2 accum_floored = ImTrunc(g.NavWindowingAccumDeltaPos);
13801
0
            if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
13802
0
            {
13803
0
                ImGuiWindow* moving_window = g.NavWindowingTarget->RootWindowDockTree;
13804
0
                SetWindowPos(moving_window, moving_window->Pos + accum_floored, ImGuiCond_Always);
13805
0
                g.NavWindowingAccumDeltaPos -= accum_floored;
13806
0
            }
13807
0
        }
13808
0
    }
13809
13810
    // Apply final focus
13811
84.9k
    if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow))
13812
0
    {
13813
        // FIXME: Many actions here could be part of a higher-level/reused function. Why aren't they in FocusWindow()
13814
        // Investigate for each of them: ClearActiveID(), NavRestoreHighlightAfterMove(), NavRestoreLastChildNavWindow(), ClosePopupsOverWindow(), NavInitWindow()
13815
0
        ImGuiViewport* previous_viewport = g.NavWindow ? g.NavWindow->Viewport : NULL;
13816
0
        ClearActiveID();
13817
0
        NavRestoreHighlightAfterMove();
13818
0
        ClosePopupsOverWindow(apply_focus_window, false);
13819
0
        FocusWindow(apply_focus_window, ImGuiFocusRequestFlags_RestoreFocusedChild);
13820
0
        apply_focus_window = g.NavWindow;
13821
0
        if (apply_focus_window->NavLastIds[0] == 0)
13822
0
            NavInitWindow(apply_focus_window, false);
13823
13824
        // If the window has ONLY a menu layer (no main layer), select it directly
13825
        // Use NavLayersActiveMaskNext since windows didn't have a chance to be Begin()-ed on this frame,
13826
        // so CTRL+Tab where the keys are only held for 1 frame will be able to use correct layers mask since
13827
        // the target window as already been previewed once.
13828
        // FIXME-NAV: This should be done in NavInit.. or in FocusWindow... However in both of those cases,
13829
        // we won't have a guarantee that windows has been visible before and therefore NavLayersActiveMask*
13830
        // won't be valid.
13831
0
        if (apply_focus_window->DC.NavLayersActiveMaskNext == (1 << ImGuiNavLayer_Menu))
13832
0
            g.NavLayer = ImGuiNavLayer_Menu;
13833
13834
        // Request OS level focus
13835
0
        if (apply_focus_window->Viewport != previous_viewport && g.PlatformIO.Platform_SetWindowFocus)
13836
0
            g.PlatformIO.Platform_SetWindowFocus(apply_focus_window->Viewport);
13837
0
    }
13838
84.9k
    if (apply_focus_window)
13839
0
        g.NavWindowingTarget = NULL;
13840
13841
    // Apply menu/layer toggle
13842
84.9k
    if (apply_toggle_layer && g.NavWindow)
13843
54
    {
13844
54
        ClearActiveID();
13845
13846
        // Move to parent menu if necessary
13847
54
        ImGuiWindow* new_nav_window = g.NavWindow;
13848
92
        while (new_nav_window->ParentWindow
13849
92
            && (new_nav_window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0
13850
92
            && (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0
13851
92
            && (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
13852
38
            new_nav_window = new_nav_window->ParentWindow;
13853
54
        if (new_nav_window != g.NavWindow)
13854
38
        {
13855
38
            ImGuiWindow* old_nav_window = g.NavWindow;
13856
38
            FocusWindow(new_nav_window);
13857
38
            new_nav_window->NavLastChildNavWindow = old_nav_window;
13858
38
        }
13859
13860
        // Toggle layer
13861
54
        const ImGuiNavLayer new_nav_layer = (g.NavWindow->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main;
13862
54
        if (new_nav_layer != g.NavLayer)
13863
54
        {
13864
            // Reinitialize navigation when entering menu bar with the Alt key (FIXME: could be a properly of the layer?)
13865
54
            const bool preserve_layer_1_nav_id = (new_nav_window->DockNodeAsHost != NULL);
13866
54
            if (new_nav_layer == ImGuiNavLayer_Menu && !preserve_layer_1_nav_id)
13867
38
                g.NavWindow->NavLastIds[new_nav_layer] = 0;
13868
54
            NavRestoreLayer(new_nav_layer);
13869
54
            NavRestoreHighlightAfterMove();
13870
54
        }
13871
54
    }
13872
84.9k
}
13873
13874
// Window has already passed the IsWindowNavFocusable()
13875
static const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window)
13876
0
{
13877
0
    if (window->Flags & ImGuiWindowFlags_Popup)
13878
0
        return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingPopup);
13879
0
    if ((window->Flags & ImGuiWindowFlags_MenuBar) && strcmp(window->Name, "##MainMenuBar") == 0)
13880
0
        return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingMainMenuBar);
13881
0
    if (window->DockNodeAsHost)
13882
0
        return "(Dock node)"; // Not normally shown to user.
13883
0
    return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingUntitled);
13884
0
}
13885
13886
// Overlay displayed when using CTRL+TAB. Called by EndFrame().
13887
void ImGui::NavUpdateWindowingOverlay()
13888
0
{
13889
0
    ImGuiContext& g = *GImGui;
13890
0
    IM_ASSERT(g.NavWindowingTarget != NULL);
13891
13892
0
    if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY)
13893
0
        return;
13894
13895
0
    if (g.NavWindowingListWindow == NULL)
13896
0
        g.NavWindowingListWindow = FindWindowByName("###NavWindowingList");
13897
0
    const ImGuiViewport* viewport = /*g.NavWindow ? g.NavWindow->Viewport :*/ GetMainViewport();
13898
0
    SetNextWindowSizeConstraints(ImVec2(viewport->Size.x * 0.20f, viewport->Size.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX));
13899
0
    SetNextWindowPos(viewport->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f));
13900
0
    PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f);
13901
0
    Begin("###NavWindowingList", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings);
13902
0
    if (g.ContextName[0] != 0)
13903
0
        SeparatorText(g.ContextName);
13904
0
    for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--)
13905
0
    {
13906
0
        ImGuiWindow* window = g.WindowsFocusOrder[n];
13907
0
        IM_ASSERT(window != NULL); // Fix static analyzers
13908
0
        if (!IsWindowNavFocusable(window))
13909
0
            continue;
13910
0
        const char* label = window->Name;
13911
0
        if (label == FindRenderedTextEnd(label))
13912
0
            label = GetFallbackWindowNameForWindowingList(window);
13913
0
        Selectable(label, g.NavWindowingTarget == window);
13914
0
    }
13915
0
    End();
13916
0
    PopStyleVar();
13917
0
}
13918
13919
13920
//-----------------------------------------------------------------------------
13921
// [SECTION] DRAG AND DROP
13922
//-----------------------------------------------------------------------------
13923
13924
bool ImGui::IsDragDropActive()
13925
0
{
13926
0
    ImGuiContext& g = *GImGui;
13927
0
    return g.DragDropActive;
13928
0
}
13929
13930
void ImGui::ClearDragDrop()
13931
0
{
13932
0
    ImGuiContext& g = *GImGui;
13933
0
    if (g.DragDropActive)
13934
0
        IMGUI_DEBUG_LOG_ACTIVEID("[dragdrop] ClearDragDrop()\n");
13935
0
    g.DragDropActive = false;
13936
0
    g.DragDropPayload.Clear();
13937
0
    g.DragDropAcceptFlags = ImGuiDragDropFlags_None;
13938
0
    g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0;
13939
0
    g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
13940
0
    g.DragDropAcceptFrameCount = -1;
13941
13942
0
    g.DragDropPayloadBufHeap.clear();
13943
0
    memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
13944
0
}
13945
13946
bool ImGui::BeginTooltipHidden()
13947
0
{
13948
0
    ImGuiContext& g = *GImGui;
13949
0
    bool ret = Begin("##Tooltip_Hidden", NULL, ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize);
13950
0
    SetWindowHiddenAndSkipItemsForCurrentFrame(g.CurrentWindow);
13951
0
    return ret;
13952
0
}
13953
13954
// When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource()
13955
// If the item has an identifier:
13956
// - This assume/require the item to be activated (typically via ButtonBehavior).
13957
// - Therefore if you want to use this with a mouse button other than left mouse button, it is up to the item itself to activate with another button.
13958
// - We then pull and use the mouse button that was used to activate the item and use it to carry on the drag.
13959
// If the item has no identifier:
13960
// - Currently always assume left mouse button.
13961
bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
13962
0
{
13963
0
    ImGuiContext& g = *GImGui;
13964
0
    ImGuiWindow* window = g.CurrentWindow;
13965
13966
    // FIXME-DRAGDROP: While in the common-most "drag from non-zero active id" case we can tell the mouse button,
13967
    // in both SourceExtern and id==0 cases we may requires something else (explicit flags or some heuristic).
13968
0
    ImGuiMouseButton mouse_button = ImGuiMouseButton_Left;
13969
13970
0
    bool source_drag_active = false;
13971
0
    ImGuiID source_id = 0;
13972
0
    ImGuiID source_parent_id = 0;
13973
0
    if ((flags & ImGuiDragDropFlags_SourceExtern) == 0)
13974
0
    {
13975
0
        source_id = g.LastItemData.ID;
13976
0
        if (source_id != 0)
13977
0
        {
13978
            // Common path: items with ID
13979
0
            if (g.ActiveId != source_id)
13980
0
                return false;
13981
0
            if (g.ActiveIdMouseButton != -1)
13982
0
                mouse_button = g.ActiveIdMouseButton;
13983
0
            if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
13984
0
                return false;
13985
0
            g.ActiveIdAllowOverlap = false;
13986
0
        }
13987
0
        else
13988
0
        {
13989
            // Uncommon path: items without ID
13990
0
            if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
13991
0
                return false;
13992
0
            if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) == 0 && (g.ActiveId == 0 || g.ActiveIdWindow != window))
13993
0
                return false;
13994
13995
            // If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to:
13996
            // A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag.
13997
0
            if (!(flags & ImGuiDragDropFlags_SourceAllowNullID))
13998
0
            {
13999
0
                IM_ASSERT(0);
14000
0
                return false;
14001
0
            }
14002
14003
            // Magic fallback to handle items with no assigned ID, e.g. Text(), Image()
14004
            // We build a throwaway ID based on current ID stack + relative AABB of items in window.
14005
            // THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING/RESIZINGG OF THE WIDGET, so if your widget moves your dragging operation will be canceled.
14006
            // We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive.
14007
            // Rely on keeping other window->LastItemXXX fields intact.
14008
0
            source_id = g.LastItemData.ID = window->GetIDFromRectangle(g.LastItemData.Rect);
14009
0
            KeepAliveID(source_id);
14010
0
            bool is_hovered = ItemHoverable(g.LastItemData.Rect, source_id, g.LastItemData.InFlags);
14011
0
            if (is_hovered && g.IO.MouseClicked[mouse_button])
14012
0
            {
14013
0
                SetActiveID(source_id, window);
14014
0
                FocusWindow(window);
14015
0
            }
14016
0
            if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker.
14017
0
                g.ActiveIdAllowOverlap = is_hovered;
14018
0
        }
14019
0
        if (g.ActiveId != source_id)
14020
0
            return false;
14021
0
        source_parent_id = window->IDStack.back();
14022
0
        source_drag_active = IsMouseDragging(mouse_button);
14023
14024
        // Disable navigation and key inputs while dragging + cancel existing request if any
14025
0
        SetActiveIdUsingAllKeyboardKeys();
14026
0
    }
14027
0
    else
14028
0
    {
14029
        // When ImGuiDragDropFlags_SourceExtern is set:
14030
0
        window = NULL;
14031
0
        source_id = ImHashStr("#SourceExtern");
14032
0
        source_drag_active = true;
14033
0
        mouse_button = g.IO.MouseDown[0] ? 0 : -1;
14034
0
        KeepAliveID(source_id);
14035
0
        SetActiveID(source_id, NULL);
14036
0
    }
14037
14038
0
    IM_ASSERT(g.DragDropWithinTarget == false); // Can't nest BeginDragDropSource() and BeginDragDropTarget()
14039
0
    if (!source_drag_active)
14040
0
        return false;
14041
14042
    // Activate drag and drop
14043
0
    if (!g.DragDropActive)
14044
0
    {
14045
0
        IM_ASSERT(source_id != 0);
14046
0
        ClearDragDrop();
14047
0
        IMGUI_DEBUG_LOG_ACTIVEID("[dragdrop] BeginDragDropSource() DragDropActive = true, source_id = 0x%08X%s\n",
14048
0
            source_id, (flags & ImGuiDragDropFlags_SourceExtern) ? " (EXTERN)" : "");
14049
0
        ImGuiPayload& payload = g.DragDropPayload;
14050
0
        payload.SourceId = source_id;
14051
0
        payload.SourceParentId = source_parent_id;
14052
0
        g.DragDropActive = true;
14053
0
        g.DragDropSourceFlags = flags;
14054
0
        g.DragDropMouseButton = mouse_button;
14055
0
        if (payload.SourceId == g.ActiveId)
14056
0
            g.ActiveIdNoClearOnFocusLoss = true;
14057
0
    }
14058
0
    g.DragDropSourceFrameCount = g.FrameCount;
14059
0
    g.DragDropWithinSource = true;
14060
14061
0
    if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
14062
0
    {
14063
        // Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit)
14064
        // We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents.
14065
0
        bool ret;
14066
0
        if (g.DragDropAcceptIdPrev && (g.DragDropAcceptFlags & ImGuiDragDropFlags_AcceptNoPreviewTooltip))
14067
0
            ret = BeginTooltipHidden();
14068
0
        else
14069
0
            ret = BeginTooltip();
14070
0
        IM_ASSERT(ret); // FIXME-NEWBEGIN: If this ever becomes false, we need to Begin("##Hidden", NULL, ImGuiWindowFlags_NoSavedSettings) + SetWindowHiddendAndSkipItemsForCurrentFrame().
14071
0
        IM_UNUSED(ret);
14072
0
    }
14073
14074
0
    if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern))
14075
0
        g.LastItemData.StatusFlags &= ~ImGuiItemStatusFlags_HoveredRect;
14076
14077
0
    return true;
14078
0
}
14079
14080
void ImGui::EndDragDropSource()
14081
0
{
14082
0
    ImGuiContext& g = *GImGui;
14083
0
    IM_ASSERT(g.DragDropActive);
14084
0
    IM_ASSERT(g.DragDropWithinSource && "Not after a BeginDragDropSource()?");
14085
14086
0
    if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
14087
0
        EndTooltip();
14088
14089
    // Discard the drag if have not called SetDragDropPayload()
14090
0
    if (g.DragDropPayload.DataFrameCount == -1)
14091
0
        ClearDragDrop();
14092
0
    g.DragDropWithinSource = false;
14093
0
}
14094
14095
// Use 'cond' to choose to submit payload on drag start or every frame
14096
bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond)
14097
0
{
14098
0
    ImGuiContext& g = *GImGui;
14099
0
    ImGuiPayload& payload = g.DragDropPayload;
14100
0
    if (cond == 0)
14101
0
        cond = ImGuiCond_Always;
14102
14103
0
    IM_ASSERT(type != NULL);
14104
0
    IM_ASSERT(strlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 32 characters long");
14105
0
    IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0));
14106
0
    IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once);
14107
0
    IM_ASSERT(payload.SourceId != 0); // Not called between BeginDragDropSource() and EndDragDropSource()
14108
14109
0
    if (cond == ImGuiCond_Always || payload.DataFrameCount == -1)
14110
0
    {
14111
        // Copy payload
14112
0
        ImStrncpy(payload.DataType, type, IM_ARRAYSIZE(payload.DataType));
14113
0
        g.DragDropPayloadBufHeap.resize(0);
14114
0
        if (data_size > sizeof(g.DragDropPayloadBufLocal))
14115
0
        {
14116
            // Store in heap
14117
0
            g.DragDropPayloadBufHeap.resize((int)data_size);
14118
0
            payload.Data = g.DragDropPayloadBufHeap.Data;
14119
0
            memcpy(payload.Data, data, data_size);
14120
0
        }
14121
0
        else if (data_size > 0)
14122
0
        {
14123
            // Store locally
14124
0
            memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
14125
0
            payload.Data = g.DragDropPayloadBufLocal;
14126
0
            memcpy(payload.Data, data, data_size);
14127
0
        }
14128
0
        else
14129
0
        {
14130
0
            payload.Data = NULL;
14131
0
        }
14132
0
        payload.DataSize = (int)data_size;
14133
0
    }
14134
0
    payload.DataFrameCount = g.FrameCount;
14135
14136
    // Return whether the payload has been accepted
14137
0
    return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1);
14138
0
}
14139
14140
bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id)
14141
0
{
14142
0
    ImGuiContext& g = *GImGui;
14143
0
    if (!g.DragDropActive)
14144
0
        return false;
14145
14146
0
    ImGuiWindow* window = g.CurrentWindow;
14147
0
    ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
14148
0
    if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree)
14149
0
        return false;
14150
0
    IM_ASSERT(id != 0);
14151
0
    if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId))
14152
0
        return false;
14153
0
    if (window->SkipItems)
14154
0
        return false;
14155
14156
0
    IM_ASSERT(g.DragDropWithinTarget == false && g.DragDropWithinSource == false); // Can't nest BeginDragDropSource() and BeginDragDropTarget()
14157
0
    g.DragDropTargetRect = bb;
14158
0
    g.DragDropTargetClipRect = window->ClipRect; // May want to be overridden by user depending on use case?
14159
0
    g.DragDropTargetId = id;
14160
0
    g.DragDropWithinTarget = true;
14161
0
    return true;
14162
0
}
14163
14164
// We don't use BeginDragDropTargetCustom() and duplicate its code because:
14165
// 1) we use LastItemData's ImGuiItemStatusFlags_HoveredRect which handles items that push a temporarily clip rectangle in their code. Calling BeginDragDropTargetCustom(LastItemRect) would not handle them.
14166
// 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can.
14167
// Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case)
14168
bool ImGui::BeginDragDropTarget()
14169
0
{
14170
0
    ImGuiContext& g = *GImGui;
14171
0
    if (!g.DragDropActive)
14172
0
        return false;
14173
14174
0
    ImGuiWindow* window = g.CurrentWindow;
14175
0
    if (!(g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect))
14176
0
        return false;
14177
0
    ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
14178
0
    if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree || window->SkipItems)
14179
0
        return false;
14180
14181
0
    const ImRect& display_rect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? g.LastItemData.DisplayRect : g.LastItemData.Rect;
14182
0
    ImGuiID id = g.LastItemData.ID;
14183
0
    if (id == 0)
14184
0
    {
14185
0
        id = window->GetIDFromRectangle(display_rect);
14186
0
        KeepAliveID(id);
14187
0
    }
14188
0
    if (g.DragDropPayload.SourceId == id)
14189
0
        return false;
14190
14191
0
    IM_ASSERT(g.DragDropWithinTarget == false && g.DragDropWithinSource == false); // Can't nest BeginDragDropSource() and BeginDragDropTarget()
14192
0
    g.DragDropTargetRect = display_rect;
14193
0
    g.DragDropTargetClipRect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasClipRect) ? g.LastItemData.ClipRect : window->ClipRect;
14194
0
    g.DragDropTargetId = id;
14195
0
    g.DragDropWithinTarget = true;
14196
0
    return true;
14197
0
}
14198
14199
bool ImGui::IsDragDropPayloadBeingAccepted()
14200
1
{
14201
1
    ImGuiContext& g = *GImGui;
14202
1
    return g.DragDropActive && g.DragDropAcceptIdPrev != 0;
14203
1
}
14204
14205
const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags)
14206
0
{
14207
0
    ImGuiContext& g = *GImGui;
14208
0
    ImGuiPayload& payload = g.DragDropPayload;
14209
0
    IM_ASSERT(g.DragDropActive);                        // Not called between BeginDragDropTarget() and EndDragDropTarget() ?
14210
0
    IM_ASSERT(payload.DataFrameCount != -1);            // Forgot to call EndDragDropTarget() ?
14211
0
    if (type != NULL && !payload.IsDataType(type))
14212
0
        return NULL;
14213
14214
    // Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints.
14215
    // NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function!
14216
0
    const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId);
14217
0
    ImRect r = g.DragDropTargetRect;
14218
0
    float r_surface = r.GetWidth() * r.GetHeight();
14219
0
    if (r_surface > g.DragDropAcceptIdCurrRectSurface)
14220
0
        return NULL;
14221
14222
0
    g.DragDropAcceptFlags = flags;
14223
0
    g.DragDropAcceptIdCurr = g.DragDropTargetId;
14224
0
    g.DragDropAcceptIdCurrRectSurface = r_surface;
14225
    //IMGUI_DEBUG_LOG("AcceptDragDropPayload(): %08X: accept\n", g.DragDropTargetId);
14226
14227
    // Render default drop visuals
14228
0
    payload.Preview = was_accepted_previously;
14229
0
    flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that live for 1 frame)
14230
0
    if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview)
14231
0
        RenderDragDropTargetRect(r, g.DragDropTargetClipRect);
14232
14233
0
    g.DragDropAcceptFrameCount = g.FrameCount;
14234
0
    if ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) && g.DragDropMouseButton == -1)
14235
0
        payload.Delivery = was_accepted_previously && (g.DragDropSourceFrameCount < g.FrameCount);
14236
0
    else
14237
0
        payload.Delivery = was_accepted_previously && !IsMouseDown(g.DragDropMouseButton); // For extern drag sources affecting OS window focus, it's easier to just test !IsMouseDown() instead of IsMouseReleased()
14238
0
    if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery))
14239
0
        return NULL;
14240
14241
0
    if (payload.Delivery)
14242
0
        IMGUI_DEBUG_LOG_ACTIVEID("[dragdrop] AcceptDragDropPayload(): 0x%08X: payload delivery\n", g.DragDropTargetId);
14243
0
    return &payload;
14244
0
}
14245
14246
// FIXME-STYLE FIXME-DRAGDROP: Settle on a proper default visuals for drop target.
14247
void ImGui::RenderDragDropTargetRect(const ImRect& bb, const ImRect& item_clip_rect)
14248
0
{
14249
0
    ImGuiContext& g = *GImGui;
14250
0
    ImGuiWindow* window = g.CurrentWindow;
14251
0
    ImRect bb_display = bb;
14252
0
    bb_display.ClipWith(item_clip_rect); // Clip THEN expand so we have a way to visualize that target is not entirely visible.
14253
0
    bb_display.Expand(3.5f);
14254
0
    bool push_clip_rect = !window->ClipRect.Contains(bb_display);
14255
0
    if (push_clip_rect)
14256
0
        window->DrawList->PushClipRectFullScreen();
14257
0
    window->DrawList->AddRect(bb_display.Min, bb_display.Max, GetColorU32(ImGuiCol_DragDropTarget), 0.0f, 0, 2.0f);
14258
0
    if (push_clip_rect)
14259
0
        window->DrawList->PopClipRect();
14260
0
}
14261
14262
const ImGuiPayload* ImGui::GetDragDropPayload()
14263
0
{
14264
0
    ImGuiContext& g = *GImGui;
14265
0
    return (g.DragDropActive && g.DragDropPayload.DataFrameCount != -1) ? &g.DragDropPayload : NULL;
14266
0
}
14267
14268
void ImGui::EndDragDropTarget()
14269
0
{
14270
0
    ImGuiContext& g = *GImGui;
14271
0
    IM_ASSERT(g.DragDropActive);
14272
0
    IM_ASSERT(g.DragDropWithinTarget);
14273
0
    g.DragDropWithinTarget = false;
14274
14275
    // Clear drag and drop state payload right after delivery
14276
0
    if (g.DragDropPayload.Delivery)
14277
0
        ClearDragDrop();
14278
0
}
14279
14280
//-----------------------------------------------------------------------------
14281
// [SECTION] LOGGING/CAPTURING
14282
//-----------------------------------------------------------------------------
14283
// All text output from the interface can be captured into tty/file/clipboard.
14284
// By default, tree nodes are automatically opened during logging.
14285
//-----------------------------------------------------------------------------
14286
14287
// Pass text data straight to log (without being displayed)
14288
static inline void LogTextV(ImGuiContext& g, const char* fmt, va_list args)
14289
0
{
14290
0
    if (g.LogFile)
14291
0
    {
14292
0
        g.LogBuffer.Buf.resize(0);
14293
0
        g.LogBuffer.appendfv(fmt, args);
14294
0
        ImFileWrite(g.LogBuffer.c_str(), sizeof(char), (ImU64)g.LogBuffer.size(), g.LogFile);
14295
0
    }
14296
0
    else
14297
0
    {
14298
0
        g.LogBuffer.appendfv(fmt, args);
14299
0
    }
14300
0
}
14301
14302
void ImGui::LogText(const char* fmt, ...)
14303
0
{
14304
0
    ImGuiContext& g = *GImGui;
14305
0
    if (!g.LogEnabled)
14306
0
        return;
14307
14308
0
    va_list args;
14309
0
    va_start(args, fmt);
14310
0
    LogTextV(g, fmt, args);
14311
0
    va_end(args);
14312
0
}
14313
14314
void ImGui::LogTextV(const char* fmt, va_list args)
14315
0
{
14316
0
    ImGuiContext& g = *GImGui;
14317
0
    if (!g.LogEnabled)
14318
0
        return;
14319
14320
0
    LogTextV(g, fmt, args);
14321
0
}
14322
14323
// Internal version that takes a position to decide on newline placement and pad items according to their depth.
14324
// We split text into individual lines to add current tree level padding
14325
// FIXME: This code is a little complicated perhaps, considering simplifying the whole system.
14326
void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end)
14327
0
{
14328
0
    ImGuiContext& g = *GImGui;
14329
0
    ImGuiWindow* window = g.CurrentWindow;
14330
14331
0
    const char* prefix = g.LogNextPrefix;
14332
0
    const char* suffix = g.LogNextSuffix;
14333
0
    g.LogNextPrefix = g.LogNextSuffix = NULL;
14334
14335
0
    if (!text_end)
14336
0
        text_end = FindRenderedTextEnd(text, text_end);
14337
14338
0
    const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + g.Style.FramePadding.y + 1);
14339
0
    if (ref_pos)
14340
0
        g.LogLinePosY = ref_pos->y;
14341
0
    if (log_new_line)
14342
0
    {
14343
0
        LogText(IM_NEWLINE);
14344
0
        g.LogLineFirstItem = true;
14345
0
    }
14346
14347
0
    if (prefix)
14348
0
        LogRenderedText(ref_pos, prefix, prefix + strlen(prefix)); // Calculate end ourself to ensure "##" are included here.
14349
14350
    // Re-adjust padding if we have popped out of our starting depth
14351
0
    if (g.LogDepthRef > window->DC.TreeDepth)
14352
0
        g.LogDepthRef = window->DC.TreeDepth;
14353
0
    const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef);
14354
14355
0
    const char* text_remaining = text;
14356
0
    for (;;)
14357
0
    {
14358
        // Split the string. Each new line (after a '\n') is followed by indentation corresponding to the current depth of our log entry.
14359
        // We don't add a trailing \n yet to allow a subsequent item on the same line to be captured.
14360
0
        const char* line_start = text_remaining;
14361
0
        const char* line_end = ImStreolRange(line_start, text_end);
14362
0
        const bool is_last_line = (line_end == text_end);
14363
0
        if (line_start != line_end || !is_last_line)
14364
0
        {
14365
0
            const int line_length = (int)(line_end - line_start);
14366
0
            const int indentation = g.LogLineFirstItem ? tree_depth * 4 : 1;
14367
0
            LogText("%*s%.*s", indentation, "", line_length, line_start);
14368
0
            g.LogLineFirstItem = false;
14369
0
            if (*line_end == '\n')
14370
0
            {
14371
0
                LogText(IM_NEWLINE);
14372
0
                g.LogLineFirstItem = true;
14373
0
            }
14374
0
        }
14375
0
        if (is_last_line)
14376
0
            break;
14377
0
        text_remaining = line_end + 1;
14378
0
    }
14379
14380
0
    if (suffix)
14381
0
        LogRenderedText(ref_pos, suffix, suffix + strlen(suffix));
14382
0
}
14383
14384
// Start logging/capturing text output
14385
void ImGui::LogBegin(ImGuiLogType type, int auto_open_depth)
14386
0
{
14387
0
    ImGuiContext& g = *GImGui;
14388
0
    ImGuiWindow* window = g.CurrentWindow;
14389
0
    IM_ASSERT(g.LogEnabled == false);
14390
0
    IM_ASSERT(g.LogFile == NULL);
14391
0
    IM_ASSERT(g.LogBuffer.empty());
14392
0
    g.LogEnabled = g.ItemUnclipByLog = true;
14393
0
    g.LogType = type;
14394
0
    g.LogNextPrefix = g.LogNextSuffix = NULL;
14395
0
    g.LogDepthRef = window->DC.TreeDepth;
14396
0
    g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault);
14397
0
    g.LogLinePosY = FLT_MAX;
14398
0
    g.LogLineFirstItem = true;
14399
0
}
14400
14401
// Important: doesn't copy underlying data, use carefully (prefix/suffix must be in scope at the time of the next LogRenderedText)
14402
void ImGui::LogSetNextTextDecoration(const char* prefix, const char* suffix)
14403
0
{
14404
0
    ImGuiContext& g = *GImGui;
14405
0
    g.LogNextPrefix = prefix;
14406
0
    g.LogNextSuffix = suffix;
14407
0
}
14408
14409
void ImGui::LogToTTY(int auto_open_depth)
14410
0
{
14411
0
    ImGuiContext& g = *GImGui;
14412
0
    if (g.LogEnabled)
14413
0
        return;
14414
0
    IM_UNUSED(auto_open_depth);
14415
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
14416
0
    LogBegin(ImGuiLogType_TTY, auto_open_depth);
14417
0
    g.LogFile = stdout;
14418
0
#endif
14419
0
}
14420
14421
// Start logging/capturing text output to given file
14422
void ImGui::LogToFile(int auto_open_depth, const char* filename)
14423
0
{
14424
0
    ImGuiContext& g = *GImGui;
14425
0
    if (g.LogEnabled)
14426
0
        return;
14427
14428
    // FIXME: We could probably open the file in text mode "at", however note that clipboard/buffer logging will still
14429
    // be subject to outputting OS-incompatible carriage return if within strings the user doesn't use IM_NEWLINE.
14430
    // By opening the file in binary mode "ab" we have consistent output everywhere.
14431
0
    if (!filename)
14432
0
        filename = g.IO.LogFilename;
14433
0
    if (!filename || !filename[0])
14434
0
        return;
14435
0
    ImFileHandle f = ImFileOpen(filename, "ab");
14436
0
    if (!f)
14437
0
    {
14438
0
        IM_ASSERT(0);
14439
0
        return;
14440
0
    }
14441
14442
0
    LogBegin(ImGuiLogType_File, auto_open_depth);
14443
0
    g.LogFile = f;
14444
0
}
14445
14446
// Start logging/capturing text output to clipboard
14447
void ImGui::LogToClipboard(int auto_open_depth)
14448
0
{
14449
0
    ImGuiContext& g = *GImGui;
14450
0
    if (g.LogEnabled)
14451
0
        return;
14452
0
    LogBegin(ImGuiLogType_Clipboard, auto_open_depth);
14453
0
}
14454
14455
void ImGui::LogToBuffer(int auto_open_depth)
14456
0
{
14457
0
    ImGuiContext& g = *GImGui;
14458
0
    if (g.LogEnabled)
14459
0
        return;
14460
0
    LogBegin(ImGuiLogType_Buffer, auto_open_depth);
14461
0
}
14462
14463
void ImGui::LogFinish()
14464
169k
{
14465
169k
    ImGuiContext& g = *GImGui;
14466
169k
    if (!g.LogEnabled)
14467
169k
        return;
14468
14469
0
    LogText(IM_NEWLINE);
14470
0
    switch (g.LogType)
14471
0
    {
14472
0
    case ImGuiLogType_TTY:
14473
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
14474
0
        fflush(g.LogFile);
14475
0
#endif
14476
0
        break;
14477
0
    case ImGuiLogType_File:
14478
0
        ImFileClose(g.LogFile);
14479
0
        break;
14480
0
    case ImGuiLogType_Buffer:
14481
0
        break;
14482
0
    case ImGuiLogType_Clipboard:
14483
0
        if (!g.LogBuffer.empty())
14484
0
            SetClipboardText(g.LogBuffer.begin());
14485
0
        break;
14486
0
    case ImGuiLogType_None:
14487
0
        IM_ASSERT(0);
14488
0
        break;
14489
0
    }
14490
14491
0
    g.LogEnabled = g.ItemUnclipByLog = false;
14492
0
    g.LogType = ImGuiLogType_None;
14493
0
    g.LogFile = NULL;
14494
0
    g.LogBuffer.clear();
14495
0
}
14496
14497
// Helper to display logging buttons
14498
// FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!)
14499
void ImGui::LogButtons()
14500
0
{
14501
0
    ImGuiContext& g = *GImGui;
14502
14503
0
    PushID("LogButtons");
14504
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
14505
0
    const bool log_to_tty = Button("Log To TTY"); SameLine();
14506
#else
14507
    const bool log_to_tty = false;
14508
#endif
14509
0
    const bool log_to_file = Button("Log To File"); SameLine();
14510
0
    const bool log_to_clipboard = Button("Log To Clipboard"); SameLine();
14511
0
    PushItemFlag(ImGuiItemFlags_NoTabStop, true);
14512
0
    SetNextItemWidth(80.0f);
14513
0
    SliderInt("Default Depth", &g.LogDepthToExpandDefault, 0, 9, NULL);
14514
0
    PopItemFlag();
14515
0
    PopID();
14516
14517
    // Start logging at the end of the function so that the buttons don't appear in the log
14518
0
    if (log_to_tty)
14519
0
        LogToTTY();
14520
0
    if (log_to_file)
14521
0
        LogToFile();
14522
0
    if (log_to_clipboard)
14523
0
        LogToClipboard();
14524
0
}
14525
14526
14527
//-----------------------------------------------------------------------------
14528
// [SECTION] SETTINGS
14529
//-----------------------------------------------------------------------------
14530
// - UpdateSettings() [Internal]
14531
// - MarkIniSettingsDirty() [Internal]
14532
// - FindSettingsHandler() [Internal]
14533
// - ClearIniSettings() [Internal]
14534
// - LoadIniSettingsFromDisk()
14535
// - LoadIniSettingsFromMemory()
14536
// - SaveIniSettingsToDisk()
14537
// - SaveIniSettingsToMemory()
14538
//-----------------------------------------------------------------------------
14539
// - CreateNewWindowSettings() [Internal]
14540
// - FindWindowSettingsByID() [Internal]
14541
// - FindWindowSettingsByWindow() [Internal]
14542
// - ClearWindowSettings() [Internal]
14543
// - WindowSettingsHandler_***() [Internal]
14544
//-----------------------------------------------------------------------------
14545
14546
// Called by NewFrame()
14547
void ImGui::UpdateSettings()
14548
84.9k
{
14549
    // Load settings on first frame (if not explicitly loaded manually before)
14550
84.9k
    ImGuiContext& g = *GImGui;
14551
84.9k
    if (!g.SettingsLoaded)
14552
1
    {
14553
1
        IM_ASSERT(g.SettingsWindows.empty());
14554
1
        if (g.IO.IniFilename)
14555
0
            LoadIniSettingsFromDisk(g.IO.IniFilename);
14556
1
        g.SettingsLoaded = true;
14557
1
    }
14558
14559
    // Save settings (with a delay after the last modification, so we don't spam disk too much)
14560
84.9k
    if (g.SettingsDirtyTimer > 0.0f)
14561
600
    {
14562
600
        g.SettingsDirtyTimer -= g.IO.DeltaTime;
14563
600
        if (g.SettingsDirtyTimer <= 0.0f)
14564
2
        {
14565
2
            if (g.IO.IniFilename != NULL)
14566
0
                SaveIniSettingsToDisk(g.IO.IniFilename);
14567
2
            else
14568
2
                g.IO.WantSaveIniSettings = true;  // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves.
14569
2
            g.SettingsDirtyTimer = 0.0f;
14570
2
        }
14571
600
    }
14572
84.9k
}
14573
14574
void ImGui::MarkIniSettingsDirty()
14575
0
{
14576
0
    ImGuiContext& g = *GImGui;
14577
0
    if (g.SettingsDirtyTimer <= 0.0f)
14578
0
        g.SettingsDirtyTimer = g.IO.IniSavingRate;
14579
0
}
14580
14581
void ImGui::MarkIniSettingsDirty(ImGuiWindow* window)
14582
22.9k
{
14583
22.9k
    ImGuiContext& g = *GImGui;
14584
22.9k
    if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings))
14585
4
        if (g.SettingsDirtyTimer <= 0.0f)
14586
2
            g.SettingsDirtyTimer = g.IO.IniSavingRate;
14587
22.9k
}
14588
14589
void ImGui::AddSettingsHandler(const ImGuiSettingsHandler* handler)
14590
2
{
14591
2
    ImGuiContext& g = *GImGui;
14592
2
    IM_ASSERT(FindSettingsHandler(handler->TypeName) == NULL);
14593
2
    g.SettingsHandlers.push_back(*handler);
14594
2
}
14595
14596
void ImGui::RemoveSettingsHandler(const char* type_name)
14597
0
{
14598
0
    ImGuiContext& g = *GImGui;
14599
0
    if (ImGuiSettingsHandler* handler = FindSettingsHandler(type_name))
14600
0
        g.SettingsHandlers.erase(handler);
14601
0
}
14602
14603
ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
14604
2
{
14605
2
    ImGuiContext& g = *GImGui;
14606
2
    const ImGuiID type_hash = ImHashStr(type_name);
14607
2
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14608
1
        if (handler.TypeHash == type_hash)
14609
0
            return &handler;
14610
2
    return NULL;
14611
2
}
14612
14613
// Clear all settings (windows, tables, docking etc.)
14614
void ImGui::ClearIniSettings()
14615
0
{
14616
0
    ImGuiContext& g = *GImGui;
14617
0
    g.SettingsIniData.clear();
14618
0
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14619
0
        if (handler.ClearAllFn != NULL)
14620
0
            handler.ClearAllFn(&g, &handler);
14621
0
}
14622
14623
void ImGui::LoadIniSettingsFromDisk(const char* ini_filename)
14624
0
{
14625
0
    size_t file_data_size = 0;
14626
0
    char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size);
14627
0
    if (!file_data)
14628
0
        return;
14629
0
    if (file_data_size > 0)
14630
0
        LoadIniSettingsFromMemory(file_data, (size_t)file_data_size);
14631
0
    IM_FREE(file_data);
14632
0
}
14633
14634
// Zero-tolerance, no error reporting, cheap .ini parsing
14635
// Set ini_size==0 to let us use strlen(ini_data). Do not call this function with a 0 if your buffer is actually empty!
14636
void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size)
14637
0
{
14638
0
    ImGuiContext& g = *GImGui;
14639
0
    IM_ASSERT(g.Initialized);
14640
    //IM_ASSERT(!g.WithinFrameScope && "Cannot be called between NewFrame() and EndFrame()");
14641
    //IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0);
14642
14643
    // For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter).
14644
    // For our convenience and to make the code simpler, we'll also write zero-terminators within the buffer. So let's create a writable copy..
14645
0
    if (ini_size == 0)
14646
0
        ini_size = strlen(ini_data);
14647
0
    g.SettingsIniData.Buf.resize((int)ini_size + 1);
14648
0
    char* const buf = g.SettingsIniData.Buf.Data;
14649
0
    char* const buf_end = buf + ini_size;
14650
0
    memcpy(buf, ini_data, ini_size);
14651
0
    buf_end[0] = 0;
14652
14653
    // Call pre-read handlers
14654
    // Some types will clear their data (e.g. dock information) some types will allow merge/override (window)
14655
0
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14656
0
        if (handler.ReadInitFn != NULL)
14657
0
            handler.ReadInitFn(&g, &handler);
14658
14659
0
    void* entry_data = NULL;
14660
0
    ImGuiSettingsHandler* entry_handler = NULL;
14661
14662
0
    char* line_end = NULL;
14663
0
    for (char* line = buf; line < buf_end; line = line_end + 1)
14664
0
    {
14665
        // Skip new lines markers, then find end of the line
14666
0
        while (*line == '\n' || *line == '\r')
14667
0
            line++;
14668
0
        line_end = line;
14669
0
        while (line_end < buf_end && *line_end != '\n' && *line_end != '\r')
14670
0
            line_end++;
14671
0
        line_end[0] = 0;
14672
0
        if (line[0] == ';')
14673
0
            continue;
14674
0
        if (line[0] == '[' && line_end > line && line_end[-1] == ']')
14675
0
        {
14676
            // Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code.
14677
0
            line_end[-1] = 0;
14678
0
            const char* name_end = line_end - 1;
14679
0
            const char* type_start = line + 1;
14680
0
            char* type_end = (char*)(void*)ImStrchrRange(type_start, name_end, ']');
14681
0
            const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL;
14682
0
            if (!type_end || !name_start)
14683
0
                continue;
14684
0
            *type_end = 0; // Overwrite first ']'
14685
0
            name_start++;  // Skip second '['
14686
0
            entry_handler = FindSettingsHandler(type_start);
14687
0
            entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL;
14688
0
        }
14689
0
        else if (entry_handler != NULL && entry_data != NULL)
14690
0
        {
14691
            // Let type handler parse the line
14692
0
            entry_handler->ReadLineFn(&g, entry_handler, entry_data, line);
14693
0
        }
14694
0
    }
14695
0
    g.SettingsLoaded = true;
14696
14697
    // [DEBUG] Restore untouched copy so it can be browsed in Metrics (not strictly necessary)
14698
0
    memcpy(buf, ini_data, ini_size);
14699
14700
    // Call post-read handlers
14701
0
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14702
0
        if (handler.ApplyAllFn != NULL)
14703
0
            handler.ApplyAllFn(&g, &handler);
14704
0
}
14705
14706
void ImGui::SaveIniSettingsToDisk(const char* ini_filename)
14707
0
{
14708
0
    ImGuiContext& g = *GImGui;
14709
0
    g.SettingsDirtyTimer = 0.0f;
14710
0
    if (!ini_filename)
14711
0
        return;
14712
14713
0
    size_t ini_data_size = 0;
14714
0
    const char* ini_data = SaveIniSettingsToMemory(&ini_data_size);
14715
0
    ImFileHandle f = ImFileOpen(ini_filename, "wt");
14716
0
    if (!f)
14717
0
        return;
14718
0
    ImFileWrite(ini_data, sizeof(char), ini_data_size, f);
14719
0
    ImFileClose(f);
14720
0
}
14721
14722
// Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer
14723
const char* ImGui::SaveIniSettingsToMemory(size_t* out_size)
14724
0
{
14725
0
    ImGuiContext& g = *GImGui;
14726
0
    g.SettingsDirtyTimer = 0.0f;
14727
0
    g.SettingsIniData.Buf.resize(0);
14728
0
    g.SettingsIniData.Buf.push_back(0);
14729
0
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14730
0
        handler.WriteAllFn(&g, &handler, &g.SettingsIniData);
14731
0
    if (out_size)
14732
0
        *out_size = (size_t)g.SettingsIniData.size();
14733
0
    return g.SettingsIniData.c_str();
14734
0
}
14735
14736
ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name)
14737
0
{
14738
0
    ImGuiContext& g = *GImGui;
14739
14740
0
    if (g.IO.ConfigDebugIniSettings == false)
14741
0
    {
14742
        // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
14743
        // Preserve the full string when ConfigDebugVerboseIniSettings is set to make .ini inspection easier.
14744
0
        if (const char* p = strstr(name, "###"))
14745
0
            name = p;
14746
0
    }
14747
0
    const size_t name_len = strlen(name);
14748
14749
    // Allocate chunk
14750
0
    const size_t chunk_size = sizeof(ImGuiWindowSettings) + name_len + 1;
14751
0
    ImGuiWindowSettings* settings = g.SettingsWindows.alloc_chunk(chunk_size);
14752
0
    IM_PLACEMENT_NEW(settings) ImGuiWindowSettings();
14753
0
    settings->ID = ImHashStr(name, name_len);
14754
0
    memcpy(settings->GetName(), name, name_len + 1);   // Store with zero terminator
14755
14756
0
    return settings;
14757
0
}
14758
14759
// We don't provide a FindWindowSettingsByName() because Docking system doesn't always hold on names.
14760
// This is called once per window .ini entry + once per newly instantiated window.
14761
ImGuiWindowSettings* ImGui::FindWindowSettingsByID(ImGuiID id)
14762
2
{
14763
2
    ImGuiContext& g = *GImGui;
14764
2
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
14765
0
        if (settings->ID == id && !settings->WantDelete)
14766
0
            return settings;
14767
2
    return NULL;
14768
2
}
14769
14770
// This is faster if you are holding on a Window already as we don't need to perform a search.
14771
ImGuiWindowSettings* ImGui::FindWindowSettingsByWindow(ImGuiWindow* window)
14772
2
{
14773
2
    ImGuiContext& g = *GImGui;
14774
2
    if (window->SettingsOffset != -1)
14775
0
        return g.SettingsWindows.ptr_from_offset(window->SettingsOffset);
14776
2
    return FindWindowSettingsByID(window->ID);
14777
2
}
14778
14779
// This will revert window to its initial state, including enabling the ImGuiCond_FirstUseEver/ImGuiCond_Once conditions once more.
14780
void ImGui::ClearWindowSettings(const char* name)
14781
0
{
14782
    //IMGUI_DEBUG_LOG("ClearWindowSettings('%s')\n", name);
14783
0
    ImGuiContext& g = *GImGui;
14784
0
    ImGuiWindow* window = FindWindowByName(name);
14785
0
    if (window != NULL)
14786
0
    {
14787
0
        window->Flags |= ImGuiWindowFlags_NoSavedSettings;
14788
0
        InitOrLoadWindowSettings(window, NULL);
14789
0
        if (window->DockId != 0)
14790
0
            DockContextProcessUndockWindow(&g, window, true);
14791
0
    }
14792
0
    if (ImGuiWindowSettings* settings = window ? FindWindowSettingsByWindow(window) : FindWindowSettingsByID(ImHashStr(name)))
14793
0
        settings->WantDelete = true;
14794
0
}
14795
14796
static void WindowSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
14797
0
{
14798
0
    ImGuiContext& g = *ctx;
14799
0
    for (ImGuiWindow* window : g.Windows)
14800
0
        window->SettingsOffset = -1;
14801
0
    g.SettingsWindows.clear();
14802
0
}
14803
14804
static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
14805
0
{
14806
0
    ImGuiID id = ImHashStr(name);
14807
0
    ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByID(id);
14808
0
    if (settings)
14809
0
        *settings = ImGuiWindowSettings(); // Clear existing if recycling previous entry
14810
0
    else
14811
0
        settings = ImGui::CreateNewWindowSettings(name);
14812
0
    settings->ID = id;
14813
0
    settings->WantApply = true;
14814
0
    return (void*)settings;
14815
0
}
14816
14817
static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
14818
0
{
14819
0
    ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry;
14820
0
    int x, y;
14821
0
    int i;
14822
0
    ImU32 u1;
14823
0
    if (sscanf(line, "Pos=%i,%i", &x, &y) == 2)             { settings->Pos = ImVec2ih((short)x, (short)y); }
14824
0
    else if (sscanf(line, "Size=%i,%i", &x, &y) == 2)       { settings->Size = ImVec2ih((short)x, (short)y); }
14825
0
    else if (sscanf(line, "ViewportId=0x%08X", &u1) == 1)   { settings->ViewportId = u1; }
14826
0
    else if (sscanf(line, "ViewportPos=%i,%i", &x, &y) == 2){ settings->ViewportPos = ImVec2ih((short)x, (short)y); }
14827
0
    else if (sscanf(line, "Collapsed=%d", &i) == 1)         { settings->Collapsed = (i != 0); }
14828
0
    else if (sscanf(line, "IsChild=%d", &i) == 1)           { settings->IsChild = (i != 0); }
14829
0
    else if (sscanf(line, "DockId=0x%X,%d", &u1, &i) == 2)  { settings->DockId = u1; settings->DockOrder = (short)i; }
14830
0
    else if (sscanf(line, "DockId=0x%X", &u1) == 1)         { settings->DockId = u1; settings->DockOrder = -1; }
14831
0
    else if (sscanf(line, "ClassId=0x%X", &u1) == 1)        { settings->ClassId = u1; }
14832
0
}
14833
14834
// Apply to existing windows (if any)
14835
static void WindowSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
14836
0
{
14837
0
    ImGuiContext& g = *ctx;
14838
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
14839
0
        if (settings->WantApply)
14840
0
        {
14841
0
            if (ImGuiWindow* window = ImGui::FindWindowByID(settings->ID))
14842
0
                ApplyWindowSettings(window, settings);
14843
0
            settings->WantApply = false;
14844
0
        }
14845
0
}
14846
14847
static void WindowSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
14848
0
{
14849
    // Gather data from windows that were active during this session
14850
    // (if a window wasn't opened in this session we preserve its settings)
14851
0
    ImGuiContext& g = *ctx;
14852
0
    for (ImGuiWindow* window : g.Windows)
14853
0
    {
14854
0
        if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
14855
0
            continue;
14856
14857
0
        ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByWindow(window);
14858
0
        if (!settings)
14859
0
        {
14860
0
            settings = ImGui::CreateNewWindowSettings(window->Name);
14861
0
            window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
14862
0
        }
14863
0
        IM_ASSERT(settings->ID == window->ID);
14864
0
        settings->Pos = ImVec2ih(window->Pos - window->ViewportPos);
14865
0
        settings->Size = ImVec2ih(window->SizeFull);
14866
0
        settings->ViewportId = window->ViewportId;
14867
0
        settings->ViewportPos = ImVec2ih(window->ViewportPos);
14868
0
        IM_ASSERT(window->DockNode == NULL || window->DockNode->ID == window->DockId);
14869
0
        settings->DockId = window->DockId;
14870
0
        settings->ClassId = window->WindowClass.ClassId;
14871
0
        settings->DockOrder = window->DockOrder;
14872
0
        settings->Collapsed = window->Collapsed;
14873
0
        settings->IsChild = (window->RootWindow != window); // Cannot rely on ImGuiWindowFlags_ChildWindow here as docked windows have this set.
14874
0
        settings->WantDelete = false;
14875
0
    }
14876
14877
    // Write to text buffer
14878
0
    buf->reserve(buf->size() + g.SettingsWindows.size() * 6); // ballpark reserve
14879
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
14880
0
    {
14881
0
        if (settings->WantDelete)
14882
0
            continue;
14883
0
        const char* settings_name = settings->GetName();
14884
0
        buf->appendf("[%s][%s]\n", handler->TypeName, settings_name);
14885
0
        if (settings->IsChild)
14886
0
        {
14887
0
            buf->appendf("IsChild=1\n");
14888
0
            buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
14889
0
        }
14890
0
        else
14891
0
        {
14892
0
            if (settings->ViewportId != 0 && settings->ViewportId != ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
14893
0
            {
14894
0
                buf->appendf("ViewportPos=%d,%d\n", settings->ViewportPos.x, settings->ViewportPos.y);
14895
0
                buf->appendf("ViewportId=0x%08X\n", settings->ViewportId);
14896
0
            }
14897
0
            if (settings->Pos.x != 0 || settings->Pos.y != 0 || settings->ViewportId == ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
14898
0
                buf->appendf("Pos=%d,%d\n", settings->Pos.x, settings->Pos.y);
14899
0
            if (settings->Size.x != 0 || settings->Size.y != 0)
14900
0
                buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
14901
0
            buf->appendf("Collapsed=%d\n", settings->Collapsed);
14902
0
            if (settings->DockId != 0)
14903
0
            {
14904
                //buf->appendf("TabId=0x%08X\n", ImHashStr("#TAB", 4, settings->ID)); // window->TabId: this is not read back but writing it makes "debugging" the .ini data easier.
14905
0
                if (settings->DockOrder == -1)
14906
0
                    buf->appendf("DockId=0x%08X\n", settings->DockId);
14907
0
                else
14908
0
                    buf->appendf("DockId=0x%08X,%d\n", settings->DockId, settings->DockOrder);
14909
0
                if (settings->ClassId != 0)
14910
0
                    buf->appendf("ClassId=0x%08X\n", settings->ClassId);
14911
0
            }
14912
0
        }
14913
0
        buf->append("\n");
14914
0
    }
14915
0
}
14916
14917
14918
//-----------------------------------------------------------------------------
14919
// [SECTION] LOCALIZATION
14920
//-----------------------------------------------------------------------------
14921
14922
void ImGui::LocalizeRegisterEntries(const ImGuiLocEntry* entries, int count)
14923
1
{
14924
1
    ImGuiContext& g = *GImGui;
14925
13
    for (int n = 0; n < count; n++)
14926
12
        g.LocalizationTable[entries[n].Key] = entries[n].Text;
14927
1
}
14928
14929
14930
//-----------------------------------------------------------------------------
14931
// [SECTION] VIEWPORTS, PLATFORM WINDOWS
14932
//-----------------------------------------------------------------------------
14933
// - GetMainViewport()
14934
// - FindViewportByID()
14935
// - FindViewportByPlatformHandle()
14936
// - SetCurrentViewport() [Internal]
14937
// - SetWindowViewport() [Internal]
14938
// - GetWindowAlwaysWantOwnViewport() [Internal]
14939
// - UpdateTryMergeWindowIntoHostViewport() [Internal]
14940
// - UpdateTryMergeWindowIntoHostViewports() [Internal]
14941
// - TranslateWindowsInViewport() [Internal]
14942
// - ScaleWindowsInViewport() [Internal]
14943
// - FindHoveredViewportFromPlatformWindowStack() [Internal]
14944
// - UpdateViewportsNewFrame() [Internal]
14945
// - UpdateViewportsEndFrame() [Internal]
14946
// - AddUpdateViewport() [Internal]
14947
// - WindowSelectViewport() [Internal]
14948
// - WindowSyncOwnedViewport() [Internal]
14949
// - UpdatePlatformWindows()
14950
// - RenderPlatformWindowsDefault()
14951
// - FindPlatformMonitorForPos() [Internal]
14952
// - FindPlatformMonitorForRect() [Internal]
14953
// - UpdateViewportPlatformMonitor() [Internal]
14954
// - DestroyPlatformWindow() [Internal]
14955
// - DestroyPlatformWindows()
14956
//-----------------------------------------------------------------------------
14957
14958
ImGuiViewport* ImGui::GetMainViewport()
14959
363k
{
14960
363k
    ImGuiContext& g = *GImGui;
14961
363k
    return g.Viewports[0];
14962
363k
}
14963
14964
// FIXME: This leaks access to viewports not listed in PlatformIO.Viewports[]. Problematic? (#4236)
14965
ImGuiViewport* ImGui::FindViewportByID(ImGuiID id)
14966
84.9k
{
14967
84.9k
    ImGuiContext& g = *GImGui;
14968
84.9k
    for (ImGuiViewportP* viewport : g.Viewports)
14969
84.9k
        if (viewport->ID == id)
14970
84.9k
            return viewport;
14971
0
    return NULL;
14972
84.9k
}
14973
14974
ImGuiViewport* ImGui::FindViewportByPlatformHandle(void* platform_handle)
14975
0
{
14976
0
    ImGuiContext& g = *GImGui;
14977
0
    for (ImGuiViewportP* viewport : g.Viewports)
14978
0
        if (viewport->PlatformHandle == platform_handle)
14979
0
            return viewport;
14980
0
    return NULL;
14981
0
}
14982
14983
void ImGui::SetCurrentViewport(ImGuiWindow* current_window, ImGuiViewportP* viewport)
14984
387k
{
14985
387k
    ImGuiContext& g = *GImGui;
14986
387k
    (void)current_window;
14987
14988
387k
    if (viewport)
14989
302k
        viewport->LastFrameActive = g.FrameCount;
14990
387k
    if (g.CurrentViewport == viewport)
14991
217k
        return;
14992
169k
    g.CurrentDpiScale = viewport ? viewport->DpiScale : 1.0f;
14993
169k
    g.CurrentViewport = viewport;
14994
    //IMGUI_DEBUG_LOG_VIEWPORT("[viewport] SetCurrentViewport changed '%s' 0x%08X\n", current_window ? current_window->Name : NULL, viewport ? viewport->ID : 0);
14995
14996
    // Notify platform layer of viewport changes
14997
    // FIXME-DPI: This is only currently used for experimenting with handling of multiple DPI
14998
169k
    if (g.CurrentViewport && g.PlatformIO.Platform_OnChangedViewport)
14999
0
        g.PlatformIO.Platform_OnChangedViewport(g.CurrentViewport);
15000
169k
}
15001
15002
void ImGui::SetWindowViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
15003
193k
{
15004
    // Abandon viewport
15005
193k
    if (window->ViewportOwned && window->Viewport->Window == window)
15006
0
        window->Viewport->Size = ImVec2(0.0f, 0.0f);
15007
15008
193k
    window->Viewport = viewport;
15009
193k
    window->ViewportId = viewport->ID;
15010
193k
    window->ViewportOwned = (viewport->Window == window);
15011
193k
}
15012
15013
static bool ImGui::GetWindowAlwaysWantOwnViewport(ImGuiWindow* window)
15014
0
{
15015
    // Tooltips and menus are not automatically forced into their own viewport when the NoMerge flag is set, however the multiplication of viewports makes them more likely to protrude and create their own.
15016
0
    ImGuiContext& g = *GImGui;
15017
0
    if (g.IO.ConfigViewportsNoAutoMerge || (window->WindowClass.ViewportFlagsOverrideSet & ImGuiViewportFlags_NoAutoMerge))
15018
0
        if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
15019
0
            if (!window->DockIsActive)
15020
0
                if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip)) == 0)
15021
0
                    if ((window->Flags & ImGuiWindowFlags_Popup) == 0 || (window->Flags & ImGuiWindowFlags_Modal) != 0)
15022
0
                        return true;
15023
0
    return false;
15024
0
}
15025
15026
static bool ImGui::UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
15027
0
{
15028
0
    ImGuiContext& g = *GImGui;
15029
0
    if (window->Viewport == viewport)
15030
0
        return false;
15031
0
    if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) == 0)
15032
0
        return false;
15033
0
    if ((viewport->Flags & ImGuiViewportFlags_IsMinimized) != 0)
15034
0
        return false;
15035
0
    if (!viewport->GetMainRect().Contains(window->Rect()))
15036
0
        return false;
15037
0
    if (GetWindowAlwaysWantOwnViewport(window))
15038
0
        return false;
15039
15040
    // FIXME: Can't use g.WindowsFocusOrder[] for root windows only as we care about Z order. If we maintained a DisplayOrder along with FocusOrder we could..
15041
0
    for (ImGuiWindow* window_behind : g.Windows)
15042
0
    {
15043
0
        if (window_behind == window)
15044
0
            break;
15045
0
        if (window_behind->WasActive && window_behind->ViewportOwned && !(window_behind->Flags & ImGuiWindowFlags_ChildWindow))
15046
0
            if (window_behind->Viewport->GetMainRect().Overlaps(window->Rect()))
15047
0
                return false;
15048
0
    }
15049
15050
    // Move to the existing viewport, Move child/hosted windows as well (FIXME-OPT: iterate child)
15051
0
    ImGuiViewportP* old_viewport = window->Viewport;
15052
0
    if (window->ViewportOwned)
15053
0
        for (int n = 0; n < g.Windows.Size; n++)
15054
0
            if (g.Windows[n]->Viewport == old_viewport)
15055
0
                SetWindowViewport(g.Windows[n], viewport);
15056
0
    SetWindowViewport(window, viewport);
15057
0
    BringWindowToDisplayFront(window);
15058
15059
0
    return true;
15060
0
}
15061
15062
// FIXME: handle 0 to N host viewports
15063
static bool ImGui::UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window)
15064
0
{
15065
0
    ImGuiContext& g = *GImGui;
15066
0
    return UpdateTryMergeWindowIntoHostViewport(window, g.Viewports[0]);
15067
0
}
15068
15069
// Translate Dear ImGui windows when a Host Viewport has been moved
15070
// (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
15071
void ImGui::TranslateWindowsInViewport(ImGuiViewportP* viewport, const ImVec2& old_pos, const ImVec2& new_pos)
15072
0
{
15073
0
    ImGuiContext& g = *GImGui;
15074
0
    IM_ASSERT(viewport->Window == NULL && (viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows));
15075
15076
    // 1) We test if ImGuiConfigFlags_ViewportsEnable was just toggled, which allows us to conveniently
15077
    // translate imgui windows from OS-window-local to absolute coordinates or vice-versa.
15078
    // 2) If it's not going to fit into the new size, keep it at same absolute position.
15079
    // One problem with this is that most Win32 applications doesn't update their render while dragging,
15080
    // and so the window will appear to teleport when releasing the mouse.
15081
0
    const bool translate_all_windows = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable);
15082
0
    ImRect test_still_fit_rect(old_pos, old_pos + viewport->Size);
15083
0
    ImVec2 delta_pos = new_pos - old_pos;
15084
0
    for (ImGuiWindow* window : g.Windows) // FIXME-OPT
15085
0
        if (translate_all_windows || (window->Viewport == viewport && test_still_fit_rect.Contains(window->Rect())))
15086
0
            TranslateWindow(window, delta_pos);
15087
0
}
15088
15089
// Scale all windows (position, size). Use when e.g. changing DPI. (This is a lossy operation!)
15090
void ImGui::ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale)
15091
0
{
15092
0
    ImGuiContext& g = *GImGui;
15093
0
    if (viewport->Window)
15094
0
    {
15095
0
        ScaleWindow(viewport->Window, scale);
15096
0
    }
15097
0
    else
15098
0
    {
15099
0
        for (ImGuiWindow* window : g.Windows)
15100
0
            if (window->Viewport == viewport)
15101
0
                ScaleWindow(window, scale);
15102
0
    }
15103
0
}
15104
15105
// If the backend doesn't set MouseLastHoveredViewport or doesn't honor ImGuiViewportFlags_NoInputs, we do a search ourselves.
15106
// A) It won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
15107
// B) It requires Platform_GetWindowFocus to be implemented by backend.
15108
ImGuiViewportP* ImGui::FindHoveredViewportFromPlatformWindowStack(const ImVec2& mouse_platform_pos)
15109
0
{
15110
0
    ImGuiContext& g = *GImGui;
15111
0
    ImGuiViewportP* best_candidate = NULL;
15112
0
    for (ImGuiViewportP* viewport : g.Viewports)
15113
0
        if (!(viewport->Flags & (ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_IsMinimized)) && viewport->GetMainRect().Contains(mouse_platform_pos))
15114
0
            if (best_candidate == NULL || best_candidate->LastFocusedStampCount < viewport->LastFocusedStampCount)
15115
0
                best_candidate = viewport;
15116
0
    return best_candidate;
15117
0
}
15118
15119
// Update viewports and monitor infos
15120
// Note that this is running even if 'ImGuiConfigFlags_ViewportsEnable' is not set, in order to clear unused viewports (if any) and update monitor info.
15121
static void ImGui::UpdateViewportsNewFrame()
15122
84.9k
{
15123
84.9k
    ImGuiContext& g = *GImGui;
15124
84.9k
    IM_ASSERT(g.PlatformIO.Viewports.Size <= g.Viewports.Size);
15125
15126
    // Update Minimized status (we need it first in order to decide if we'll apply Pos/Size of the main viewport)
15127
    // Update Focused status
15128
84.9k
    const bool viewports_enabled = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != 0;
15129
84.9k
    if (viewports_enabled)
15130
0
    {
15131
0
        ImGuiViewportP* focused_viewport = NULL;
15132
0
        for (ImGuiViewportP* viewport : g.Viewports)
15133
0
        {
15134
0
            const bool platform_funcs_available = viewport->PlatformWindowCreated;
15135
0
            if (g.PlatformIO.Platform_GetWindowMinimized && platform_funcs_available)
15136
0
            {
15137
0
                bool is_minimized = g.PlatformIO.Platform_GetWindowMinimized(viewport);
15138
0
                if (is_minimized)
15139
0
                    viewport->Flags |= ImGuiViewportFlags_IsMinimized;
15140
0
                else
15141
0
                    viewport->Flags &= ~ImGuiViewportFlags_IsMinimized;
15142
0
            }
15143
15144
            // Update our implicit z-order knowledge of platform windows, which is used when the backend cannot provide io.MouseHoveredViewport.
15145
            // When setting Platform_GetWindowFocus, it is expected that the platform backend can handle calls without crashing if it doesn't have data stored.
15146
0
            if (g.PlatformIO.Platform_GetWindowFocus && platform_funcs_available)
15147
0
            {
15148
0
                bool is_focused = g.PlatformIO.Platform_GetWindowFocus(viewport);
15149
0
                if (is_focused)
15150
0
                    viewport->Flags |= ImGuiViewportFlags_IsFocused;
15151
0
                else
15152
0
                    viewport->Flags &= ~ImGuiViewportFlags_IsFocused;
15153
0
                if (is_focused)
15154
0
                    focused_viewport = viewport;
15155
0
            }
15156
0
        }
15157
15158
        // Focused viewport has changed?
15159
0
        if (focused_viewport && g.PlatformLastFocusedViewportId != focused_viewport->ID)
15160
0
        {
15161
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Focused viewport changed %08X -> %08X, attempting to apply our focus.\n", g.PlatformLastFocusedViewportId, focused_viewport->ID);
15162
0
            const ImGuiViewport* prev_focused_viewport = FindViewportByID(g.PlatformLastFocusedViewportId);
15163
0
            const bool prev_focused_has_been_destroyed = (prev_focused_viewport == NULL) || (prev_focused_viewport->PlatformWindowCreated == false);
15164
15165
            // Store a tag so we can infer z-order easily from all our windows
15166
            // We compare PlatformLastFocusedViewportId so newly created viewports with _NoFocusOnAppearing flag
15167
            // will keep the front most stamp instead of losing it back to their parent viewport.
15168
0
            if (focused_viewport->LastFocusedStampCount != g.ViewportFocusedStampCount)
15169
0
                focused_viewport->LastFocusedStampCount = ++g.ViewportFocusedStampCount;
15170
0
            g.PlatformLastFocusedViewportId = focused_viewport->ID;
15171
15172
            // Focus associated dear imgui window
15173
            // - if focus didn't happen with a click within imgui boundaries, e.g. Clicking platform title bar. (#6299)
15174
            // - if focus didn't happen because we destroyed another window (#6462)
15175
            // FIXME: perhaps 'FocusTopMostWindowUnderOne()' can handle the 'focused_window->Window != NULL' case as well.
15176
0
            const bool apply_imgui_focus_on_focused_viewport = !IsAnyMouseDown() && !prev_focused_has_been_destroyed;
15177
0
            if (apply_imgui_focus_on_focused_viewport)
15178
0
            {
15179
0
                focused_viewport->LastFocusedHadNavWindow |= (g.NavWindow != NULL) && (g.NavWindow->Viewport == focused_viewport); // Update so a window changing viewport won't lose focus.
15180
0
                ImGuiFocusRequestFlags focus_request_flags = ImGuiFocusRequestFlags_UnlessBelowModal | ImGuiFocusRequestFlags_RestoreFocusedChild;
15181
0
                if (focused_viewport->Window != NULL)
15182
0
                    FocusWindow(focused_viewport->Window, focus_request_flags);
15183
0
                else if (focused_viewport->LastFocusedHadNavWindow)
15184
0
                    FocusTopMostWindowUnderOne(NULL, NULL, focused_viewport, focus_request_flags); // Focus top most in viewport
15185
0
                else
15186
0
                    FocusWindow(NULL, focus_request_flags); // No window had focus last time viewport was focused
15187
0
            }
15188
0
        }
15189
0
        if (focused_viewport)
15190
0
            focused_viewport->LastFocusedHadNavWindow = (g.NavWindow != NULL) && (g.NavWindow->Viewport == focused_viewport);
15191
0
    }
15192
15193
    // Create/update main viewport with current platform position.
15194
    // FIXME-VIEWPORT: Size is driven by backend/user code for backward-compatibility but we should aim to make this more consistent.
15195
84.9k
    ImGuiViewportP* main_viewport = g.Viewports[0];
15196
84.9k
    IM_ASSERT(main_viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID);
15197
84.9k
    IM_ASSERT(main_viewport->Window == NULL);
15198
84.9k
    ImVec2 main_viewport_pos = viewports_enabled ? g.PlatformIO.Platform_GetWindowPos(main_viewport) : ImVec2(0.0f, 0.0f);
15199
84.9k
    ImVec2 main_viewport_size = g.IO.DisplaySize;
15200
84.9k
    if (viewports_enabled && (main_viewport->Flags & ImGuiViewportFlags_IsMinimized))
15201
0
    {
15202
0
        main_viewport_pos = main_viewport->Pos;    // Preserve last pos/size when minimized (FIXME: We don't do the same for Size outside of the viewport path)
15203
0
        main_viewport_size = main_viewport->Size;
15204
0
    }
15205
84.9k
    AddUpdateViewport(NULL, IMGUI_VIEWPORT_DEFAULT_ID, main_viewport_pos, main_viewport_size, ImGuiViewportFlags_OwnedByApp | ImGuiViewportFlags_CanHostOtherWindows);
15206
15207
84.9k
    g.CurrentDpiScale = 0.0f;
15208
84.9k
    g.CurrentViewport = NULL;
15209
84.9k
    g.MouseViewport = NULL;
15210
169k
    for (int n = 0; n < g.Viewports.Size; n++)
15211
84.9k
    {
15212
84.9k
        ImGuiViewportP* viewport = g.Viewports[n];
15213
84.9k
        viewport->Idx = n;
15214
15215
        // Erase unused viewports
15216
84.9k
        if (n > 0 && viewport->LastFrameActive < g.FrameCount - 2)
15217
0
        {
15218
0
            DestroyViewport(viewport);
15219
0
            n--;
15220
0
            continue;
15221
0
        }
15222
15223
84.9k
        const bool platform_funcs_available = viewport->PlatformWindowCreated;
15224
84.9k
        if (viewports_enabled)
15225
0
        {
15226
            // Update Position and Size (from Platform Window to ImGui) if requested.
15227
            // We do it early in the frame instead of waiting for UpdatePlatformWindows() to avoid a frame of lag when moving/resizing using OS facilities.
15228
0
            if (!(viewport->Flags & ImGuiViewportFlags_IsMinimized) && platform_funcs_available)
15229
0
            {
15230
                // Viewport->WorkPos and WorkSize will be updated below
15231
0
                if (viewport->PlatformRequestMove)
15232
0
                    viewport->Pos = viewport->LastPlatformPos = g.PlatformIO.Platform_GetWindowPos(viewport);
15233
0
                if (viewport->PlatformRequestResize)
15234
0
                    viewport->Size = viewport->LastPlatformSize = g.PlatformIO.Platform_GetWindowSize(viewport);
15235
0
            }
15236
0
        }
15237
15238
        // Update/copy monitor info
15239
84.9k
        UpdateViewportPlatformMonitor(viewport);
15240
15241
        // Lock down space taken by menu bars and status bars + query initial insets from backend
15242
        // Setup initial value for functions like BeginMainMenuBar(), DockSpaceOverViewport() etc.
15243
84.9k
        viewport->WorkInsetMin = viewport->BuildWorkInsetMin;
15244
84.9k
        viewport->WorkInsetMax = viewport->BuildWorkInsetMax;
15245
84.9k
        viewport->BuildWorkInsetMin = viewport->BuildWorkInsetMax = ImVec2(0.0f, 0.0f);
15246
84.9k
        if (g.PlatformIO.Platform_GetWindowWorkAreaInsets != NULL)
15247
0
        {
15248
0
            ImVec4 insets = g.PlatformIO.Platform_GetWindowWorkAreaInsets(viewport);
15249
0
            IM_ASSERT(insets.x >= 0.0f && insets.y >= 0.0f && insets.z >= 0.0f && insets.w >= 0.0f);
15250
0
            viewport->BuildWorkInsetMin = ImVec2(insets.x, insets.y);
15251
0
            viewport->BuildWorkInsetMax = ImVec2(insets.z, insets.w);
15252
0
        }
15253
84.9k
        viewport->UpdateWorkRect();
15254
15255
        // Reset alpha every frame. Users of transparency (docking) needs to request a lower alpha back.
15256
84.9k
        viewport->Alpha = 1.0f;
15257
15258
        // Translate Dear ImGui windows when a Host Viewport has been moved
15259
        // (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
15260
84.9k
        const ImVec2 viewport_delta_pos = viewport->Pos - viewport->LastPos;
15261
84.9k
        if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) && (viewport_delta_pos.x != 0.0f || viewport_delta_pos.y != 0.0f))
15262
0
            TranslateWindowsInViewport(viewport, viewport->LastPos, viewport->Pos);
15263
15264
        // Update DPI scale
15265
84.9k
        float new_dpi_scale;
15266
84.9k
        if (g.PlatformIO.Platform_GetWindowDpiScale && platform_funcs_available)
15267
0
            new_dpi_scale = g.PlatformIO.Platform_GetWindowDpiScale(viewport);
15268
84.9k
        else if (viewport->PlatformMonitor != -1)
15269
0
            new_dpi_scale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
15270
84.9k
        else
15271
84.9k
            new_dpi_scale = (viewport->DpiScale != 0.0f) ? viewport->DpiScale : 1.0f;
15272
84.9k
        if (viewport->DpiScale != 0.0f && new_dpi_scale != viewport->DpiScale)
15273
0
        {
15274
0
            float scale_factor = new_dpi_scale / viewport->DpiScale;
15275
0
            if (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleViewports)
15276
0
                ScaleWindowsInViewport(viewport, scale_factor);
15277
            //if (viewport == GetMainViewport())
15278
            //    g.PlatformInterface.SetWindowSize(viewport, viewport->Size * scale_factor);
15279
15280
            // Scale our window moving pivot so that the window will rescale roughly around the mouse position.
15281
            // FIXME-VIEWPORT: This currently creates a resizing feedback loop when a window is straddling a DPI transition border.
15282
            // (Minor: since our sizes do not perfectly linearly scale, deferring the click offset scale until we know the actual window scale ratio may get us slightly more precise mouse positioning.)
15283
            //if (g.MovingWindow != NULL && g.MovingWindow->Viewport == viewport)
15284
            //    g.ActiveIdClickOffset = ImTrunc(g.ActiveIdClickOffset * scale_factor);
15285
0
        }
15286
84.9k
        viewport->DpiScale = new_dpi_scale;
15287
84.9k
    }
15288
15289
    // Update fallback monitor
15290
84.9k
    g.PlatformMonitorsFullWorkRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);
15291
84.9k
    if (g.PlatformIO.Monitors.Size == 0)
15292
84.9k
    {
15293
84.9k
        ImGuiPlatformMonitor* monitor = &g.FallbackMonitor;
15294
84.9k
        monitor->MainPos = main_viewport->Pos;
15295
84.9k
        monitor->MainSize = main_viewport->Size;
15296
84.9k
        monitor->WorkPos = main_viewport->WorkPos;
15297
84.9k
        monitor->WorkSize = main_viewport->WorkSize;
15298
84.9k
        monitor->DpiScale = main_viewport->DpiScale;
15299
84.9k
        g.PlatformMonitorsFullWorkRect.Add(monitor->WorkPos);
15300
84.9k
        g.PlatformMonitorsFullWorkRect.Add(monitor->WorkPos + monitor->WorkSize);
15301
84.9k
    }
15302
0
    else
15303
0
    {
15304
0
        g.FallbackMonitor = g.PlatformIO.Monitors[0];
15305
0
    }
15306
84.9k
    for (ImGuiPlatformMonitor& monitor : g.PlatformIO.Monitors)
15307
0
    {
15308
0
        g.PlatformMonitorsFullWorkRect.Add(monitor.WorkPos);
15309
0
        g.PlatformMonitorsFullWorkRect.Add(monitor.WorkPos + monitor.WorkSize);
15310
0
    }
15311
15312
84.9k
    if (!viewports_enabled)
15313
84.9k
    {
15314
84.9k
        g.MouseViewport = main_viewport;
15315
84.9k
        return;
15316
84.9k
    }
15317
15318
    // Mouse handling: decide on the actual mouse viewport for this frame between the active/focused viewport and the hovered viewport.
15319
    // Note that 'viewport_hovered' should skip over any viewport that has the ImGuiViewportFlags_NoInputs flags set.
15320
0
    ImGuiViewportP* viewport_hovered = NULL;
15321
0
    if (g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport)
15322
0
    {
15323
0
        viewport_hovered = g.IO.MouseHoveredViewport ? (ImGuiViewportP*)FindViewportByID(g.IO.MouseHoveredViewport) : NULL;
15324
0
        if (viewport_hovered && (viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
15325
0
            viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos); // Backend failed to handle _NoInputs viewport: revert to our fallback.
15326
0
    }
15327
0
    else
15328
0
    {
15329
        // If the backend doesn't know how to honor ImGuiViewportFlags_NoInputs, we do a search ourselves. Note that this search:
15330
        // A) won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
15331
        // B) won't take account of how the backend apply parent<>child relationship to secondary viewports, which affects their Z order.
15332
        // C) uses LastFrameAsRefViewport as a flawed replacement for the last time a window was focused (we could/should fix that by introducing Focus functions in PlatformIO)
15333
0
        viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos);
15334
0
    }
15335
0
    if (viewport_hovered != NULL)
15336
0
        g.MouseLastHoveredViewport = viewport_hovered;
15337
0
    else if (g.MouseLastHoveredViewport == NULL)
15338
0
        g.MouseLastHoveredViewport = g.Viewports[0];
15339
15340
    // Update mouse reference viewport
15341
    // (when moving a window we aim at its viewport, but this will be overwritten below if we go in drag and drop mode)
15342
    // (MovingViewport->Viewport will be NULL in the rare situation where the window disappared while moving, set UpdateMouseMovingWindowNewFrame() for details)
15343
0
    if (g.MovingWindow && g.MovingWindow->Viewport)
15344
0
        g.MouseViewport = g.MovingWindow->Viewport;
15345
0
    else
15346
0
        g.MouseViewport = g.MouseLastHoveredViewport;
15347
15348
    // When dragging something, always refer to the last hovered viewport.
15349
    // - when releasing a moving window we will revert to aiming behind (at viewport_hovered)
15350
    // - when we are between viewports, our dragged preview will tend to show in the last viewport _even_ if we don't have tooltips in their viewports (when lacking monitor info)
15351
    // - consider the case of holding on a menu item to browse child menus: even thou a mouse button is held, there's no active id because menu items only react on mouse release.
15352
    // FIXME-VIEWPORT: This is essentially broken, when ImGuiBackendFlags_HasMouseHoveredViewport is set we want to trust when viewport_hovered==NULL and use that.
15353
0
    const bool is_mouse_dragging_with_an_expected_destination = g.DragDropActive;
15354
0
    if (is_mouse_dragging_with_an_expected_destination && viewport_hovered == NULL)
15355
0
        viewport_hovered = g.MouseLastHoveredViewport;
15356
0
    if (is_mouse_dragging_with_an_expected_destination || g.ActiveId == 0 || !IsAnyMouseDown())
15357
0
        if (viewport_hovered != NULL && viewport_hovered != g.MouseViewport && !(viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
15358
0
            g.MouseViewport = viewport_hovered;
15359
15360
0
    IM_ASSERT(g.MouseViewport != NULL);
15361
0
}
15362
15363
// Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
15364
static void ImGui::UpdateViewportsEndFrame()
15365
84.9k
{
15366
84.9k
    ImGuiContext& g = *GImGui;
15367
84.9k
    g.PlatformIO.Viewports.resize(0);
15368
169k
    for (int i = 0; i < g.Viewports.Size; i++)
15369
84.9k
    {
15370
84.9k
        ImGuiViewportP* viewport = g.Viewports[i];
15371
84.9k
        viewport->LastPos = viewport->Pos;
15372
84.9k
        if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0.0f || viewport->Size.y <= 0.0f)
15373
0
            if (i > 0) // Always include main viewport in the list
15374
0
                continue;
15375
84.9k
        if (viewport->Window && !IsWindowActiveAndVisible(viewport->Window))
15376
0
            continue;
15377
84.9k
        if (i > 0)
15378
84.9k
            IM_ASSERT(viewport->Window != NULL);
15379
84.9k
        g.PlatformIO.Viewports.push_back(viewport);
15380
84.9k
    }
15381
84.9k
    g.Viewports[0]->ClearRequestFlags(); // Clear main viewport flags because UpdatePlatformWindows() won't do it and may not even be called
15382
84.9k
}
15383
15384
// FIXME: We should ideally refactor the system to call this every frame (we currently don't)
15385
ImGuiViewportP* ImGui::AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& pos, const ImVec2& size, ImGuiViewportFlags flags)
15386
84.9k
{
15387
84.9k
    ImGuiContext& g = *GImGui;
15388
84.9k
    IM_ASSERT(id != 0);
15389
15390
84.9k
    flags |= ImGuiViewportFlags_IsPlatformWindow;
15391
84.9k
    if (window != NULL)
15392
0
    {
15393
0
        if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window)
15394
0
            flags |= ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_NoFocusOnAppearing;
15395
0
        if ((window->Flags & ImGuiWindowFlags_NoMouseInputs) && (window->Flags & ImGuiWindowFlags_NoNavInputs))
15396
0
            flags |= ImGuiViewportFlags_NoInputs;
15397
0
        if (window->Flags & ImGuiWindowFlags_NoFocusOnAppearing)
15398
0
            flags |= ImGuiViewportFlags_NoFocusOnAppearing;
15399
0
    }
15400
15401
84.9k
    ImGuiViewportP* viewport = (ImGuiViewportP*)FindViewportByID(id);
15402
84.9k
    if (viewport)
15403
84.9k
    {
15404
        // Always update for main viewport as we are already pulling correct platform pos/size (see #4900)
15405
84.9k
        if (!viewport->PlatformRequestMove || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
15406
84.9k
            viewport->Pos = pos;
15407
84.9k
        if (!viewport->PlatformRequestResize || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
15408
84.9k
            viewport->Size = size;
15409
84.9k
        viewport->Flags = flags | (viewport->Flags & (ImGuiViewportFlags_IsMinimized | ImGuiViewportFlags_IsFocused)); // Preserve existing flags
15410
84.9k
    }
15411
0
    else
15412
0
    {
15413
        // New viewport
15414
0
        viewport = IM_NEW(ImGuiViewportP)();
15415
0
        viewport->ID = id;
15416
0
        viewport->Idx = g.Viewports.Size;
15417
0
        viewport->Pos = viewport->LastPos = pos;
15418
0
        viewport->Size = size;
15419
0
        viewport->Flags = flags;
15420
0
        UpdateViewportPlatformMonitor(viewport);
15421
0
        g.Viewports.push_back(viewport);
15422
0
        g.ViewportCreatedCount++;
15423
0
        IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Add Viewport %08X '%s'\n", id, window ? window->Name : "<NULL>");
15424
15425
        // We normally setup for all viewports in NewFrame() but here need to handle the mid-frame creation of a new viewport.
15426
        // We need to extend the fullscreen clip rect so the OverlayDrawList clip is correct for that the first frame
15427
0
        g.DrawListSharedData.ClipRectFullscreen.x = ImMin(g.DrawListSharedData.ClipRectFullscreen.x, viewport->Pos.x);
15428
0
        g.DrawListSharedData.ClipRectFullscreen.y = ImMin(g.DrawListSharedData.ClipRectFullscreen.y, viewport->Pos.y);
15429
0
        g.DrawListSharedData.ClipRectFullscreen.z = ImMax(g.DrawListSharedData.ClipRectFullscreen.z, viewport->Pos.x + viewport->Size.x);
15430
0
        g.DrawListSharedData.ClipRectFullscreen.w = ImMax(g.DrawListSharedData.ClipRectFullscreen.w, viewport->Pos.y + viewport->Size.y);
15431
15432
        // Store initial DpiScale before the OS platform window creation, based on expected monitor data.
15433
        // This is so we can select an appropriate font size on the first frame of our window lifetime
15434
0
        if (viewport->PlatformMonitor != -1)
15435
0
            viewport->DpiScale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
15436
0
    }
15437
15438
84.9k
    viewport->Window = window;
15439
84.9k
    viewport->LastFrameActive = g.FrameCount;
15440
84.9k
    viewport->UpdateWorkRect();
15441
84.9k
    IM_ASSERT(window == NULL || viewport->ID == window->ID);
15442
15443
84.9k
    if (window != NULL)
15444
0
        window->ViewportOwned = true;
15445
15446
84.9k
    return viewport;
15447
84.9k
}
15448
15449
static void ImGui::DestroyViewport(ImGuiViewportP* viewport)
15450
0
{
15451
    // Clear references to this viewport in windows (window->ViewportId becomes the master data)
15452
0
    ImGuiContext& g = *GImGui;
15453
0
    for (ImGuiWindow* window : g.Windows)
15454
0
    {
15455
0
        if (window->Viewport != viewport)
15456
0
            continue;
15457
0
        window->Viewport = NULL;
15458
0
        window->ViewportOwned = false;
15459
0
    }
15460
0
    if (viewport == g.MouseLastHoveredViewport)
15461
0
        g.MouseLastHoveredViewport = NULL;
15462
15463
    // Destroy
15464
0
    IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Delete Viewport %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
15465
0
    DestroyPlatformWindow(viewport); // In most circumstances the platform window will already be destroyed here.
15466
0
    IM_ASSERT(g.PlatformIO.Viewports.contains(viewport) == false);
15467
0
    IM_ASSERT(g.Viewports[viewport->Idx] == viewport);
15468
0
    g.Viewports.erase(g.Viewports.Data + viewport->Idx);
15469
0
    IM_DELETE(viewport);
15470
0
}
15471
15472
// FIXME-VIEWPORT: This is all super messy and ought to be clarified or rewritten.
15473
static void ImGui::WindowSelectViewport(ImGuiWindow* window)
15474
193k
{
15475
193k
    ImGuiContext& g = *GImGui;
15476
193k
    ImGuiWindowFlags flags = window->Flags;
15477
193k
    window->ViewportAllowPlatformMonitorExtend = -1;
15478
15479
    // Restore main viewport if multi-viewport is not supported by the backend
15480
193k
    ImGuiViewportP* main_viewport = (ImGuiViewportP*)(void*)GetMainViewport();
15481
193k
    if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
15482
193k
    {
15483
193k
        SetWindowViewport(window, main_viewport);
15484
193k
        return;
15485
193k
    }
15486
0
    window->ViewportOwned = false;
15487
15488
    // Appearing popups reset their viewport so they can inherit again
15489
0
    if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && window->Appearing)
15490
0
    {
15491
0
        window->Viewport = NULL;
15492
0
        window->ViewportId = 0;
15493
0
    }
15494
15495
0
    if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport) == 0)
15496
0
    {
15497
        // By default inherit from parent window
15498
0
        if (window->Viewport == NULL && window->ParentWindow && (!window->ParentWindow->IsFallbackWindow || window->ParentWindow->WasActive))
15499
0
            window->Viewport = window->ParentWindow->Viewport;
15500
15501
        // Attempt to restore saved viewport id (= window that hasn't been activated yet), try to restore the viewport based on saved 'window->ViewportPos' restored from .ini file
15502
0
        if (window->Viewport == NULL && window->ViewportId != 0)
15503
0
        {
15504
0
            window->Viewport = (ImGuiViewportP*)FindViewportByID(window->ViewportId);
15505
0
            if (window->Viewport == NULL && window->ViewportPos.x != FLT_MAX && window->ViewportPos.y != FLT_MAX)
15506
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->ViewportPos, window->Size, ImGuiViewportFlags_None);
15507
0
        }
15508
0
    }
15509
15510
0
    bool lock_viewport = false;
15511
0
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport)
15512
0
    {
15513
        // Code explicitly request a viewport
15514
0
        window->Viewport = (ImGuiViewportP*)FindViewportByID(g.NextWindowData.ViewportId);
15515
0
        window->ViewportId = g.NextWindowData.ViewportId; // Store ID even if Viewport isn't resolved yet.
15516
0
        if (window->Viewport && (window->Flags & ImGuiWindowFlags_DockNodeHost) != 0 && window->Viewport->Window != NULL)
15517
0
        {
15518
0
            window->Viewport->Window = window;
15519
0
            window->Viewport->ID = window->ViewportId = window->ID; // Overwrite ID (always owned by node)
15520
0
        }
15521
0
        lock_viewport = true;
15522
0
    }
15523
0
    else if ((flags & ImGuiWindowFlags_ChildWindow) || (flags & ImGuiWindowFlags_ChildMenu))
15524
0
    {
15525
        // Always inherit viewport from parent window
15526
0
        if (window->DockNode && window->DockNode->HostWindow)
15527
0
            IM_ASSERT(window->DockNode->HostWindow->Viewport == window->ParentWindow->Viewport);
15528
0
        window->Viewport = window->ParentWindow->Viewport;
15529
0
    }
15530
0
    else if (window->DockNode && window->DockNode->HostWindow)
15531
0
    {
15532
        // This covers the "always inherit viewport from parent window" case for when a window reattach to a node that was just created mid-frame
15533
0
        window->Viewport = window->DockNode->HostWindow->Viewport;
15534
0
    }
15535
0
    else if (flags & ImGuiWindowFlags_Tooltip)
15536
0
    {
15537
0
        window->Viewport = g.MouseViewport;
15538
0
    }
15539
0
    else if (GetWindowAlwaysWantOwnViewport(window))
15540
0
    {
15541
0
        window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
15542
0
    }
15543
0
    else if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window && IsMousePosValid())
15544
0
    {
15545
0
        if (window->Viewport != NULL && window->Viewport->Window == window)
15546
0
            window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
15547
0
    }
15548
0
    else
15549
0
    {
15550
        // Merge into host viewport?
15551
        // We cannot test window->ViewportOwned as it set lower in the function.
15552
        // Testing (g.ActiveId == 0 || g.ActiveIdAllowOverlap) to avoid merging during a short-term widget interaction. Main intent was to avoid during resize (see #4212)
15553
0
        bool try_to_merge_into_host_viewport = (window->Viewport && window == window->Viewport->Window && (g.ActiveId == 0 || g.ActiveIdAllowOverlap));
15554
0
        if (try_to_merge_into_host_viewport)
15555
0
            UpdateTryMergeWindowIntoHostViewports(window);
15556
0
    }
15557
15558
    // Fallback: merge in default viewport if z-order matches, otherwise create a new viewport
15559
0
    if (window->Viewport == NULL)
15560
0
        if (!UpdateTryMergeWindowIntoHostViewport(window, main_viewport))
15561
0
            window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
15562
15563
    // Mark window as allowed to protrude outside of its viewport and into the current monitor
15564
0
    if (!lock_viewport)
15565
0
    {
15566
0
        if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
15567
0
        {
15568
            // We need to take account of the possibility that mouse may become invalid.
15569
            // Popups/Tooltip always set ViewportAllowPlatformMonitorExtend so GetWindowAllowedExtentRect() will return full monitor bounds.
15570
0
            ImVec2 mouse_ref = (flags & ImGuiWindowFlags_Tooltip) ? g.IO.MousePos : g.BeginPopupStack.back().OpenMousePos;
15571
0
            bool use_mouse_ref = (g.NavDisableHighlight || !g.NavDisableMouseHover || !g.NavWindow);
15572
0
            bool mouse_valid = IsMousePosValid(&mouse_ref);
15573
0
            if ((window->Appearing || (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_ChildMenu))) && (!use_mouse_ref || mouse_valid))
15574
0
                window->ViewportAllowPlatformMonitorExtend = FindPlatformMonitorForPos((use_mouse_ref && mouse_valid) ? mouse_ref : NavCalcPreferredRefPos());
15575
0
            else
15576
0
                window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
15577
0
        }
15578
0
        else if (window->Viewport && window != window->Viewport->Window && window->Viewport->Window && !(flags & ImGuiWindowFlags_ChildWindow) && window->DockNode == NULL)
15579
0
        {
15580
            // When called from Begin() we don't have access to a proper version of the Hidden flag yet, so we replicate this code.
15581
0
            const bool will_be_visible = (window->DockIsActive && !window->DockTabIsVisible) ? false : true;
15582
0
            if ((window->Flags & ImGuiWindowFlags_DockNodeHost) && window->Viewport->LastFrameActive < g.FrameCount && will_be_visible)
15583
0
            {
15584
                // Steal/transfer ownership
15585
0
                IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' steal Viewport %08X from Window '%s'\n", window->Name, window->Viewport->ID, window->Viewport->Window->Name);
15586
0
                window->Viewport->Window = window;
15587
0
                window->Viewport->ID = window->ID;
15588
0
                window->Viewport->LastNameHash = 0;
15589
0
            }
15590
0
            else if (!UpdateTryMergeWindowIntoHostViewports(window)) // Merge?
15591
0
            {
15592
                // New viewport
15593
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
15594
0
            }
15595
0
        }
15596
0
        else if (window->ViewportAllowPlatformMonitorExtend < 0 && (flags & ImGuiWindowFlags_ChildWindow) == 0)
15597
0
        {
15598
            // Regular (non-child, non-popup) windows by default are also allowed to protrude
15599
            // Child windows are kept contained within their parent.
15600
0
            window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
15601
0
        }
15602
0
    }
15603
15604
    // Update flags
15605
0
    window->ViewportOwned = (window == window->Viewport->Window);
15606
0
    window->ViewportId = window->Viewport->ID;
15607
15608
    // If the OS window has a title bar, hide our imgui title bar
15609
    //if (window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration))
15610
    //    window->Flags |= ImGuiWindowFlags_NoTitleBar;
15611
0
}
15612
15613
void ImGui::WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack)
15614
0
{
15615
0
    ImGuiContext& g = *GImGui;
15616
15617
0
    bool viewport_rect_changed = false;
15618
15619
    // Synchronize window --> viewport in most situations
15620
    // Synchronize viewport -> window in case the platform window has been moved or resized from the OS/WM
15621
0
    if (window->Viewport->PlatformRequestMove)
15622
0
    {
15623
0
        window->Pos = window->Viewport->Pos;
15624
0
        MarkIniSettingsDirty(window);
15625
0
    }
15626
0
    else if (memcmp(&window->Viewport->Pos, &window->Pos, sizeof(window->Pos)) != 0)
15627
0
    {
15628
0
        viewport_rect_changed = true;
15629
0
        window->Viewport->Pos = window->Pos;
15630
0
    }
15631
15632
0
    if (window->Viewport->PlatformRequestResize)
15633
0
    {
15634
0
        window->Size = window->SizeFull = window->Viewport->Size;
15635
0
        MarkIniSettingsDirty(window);
15636
0
    }
15637
0
    else if (memcmp(&window->Viewport->Size, &window->Size, sizeof(window->Size)) != 0)
15638
0
    {
15639
0
        viewport_rect_changed = true;
15640
0
        window->Viewport->Size = window->Size;
15641
0
    }
15642
0
    window->Viewport->UpdateWorkRect();
15643
15644
    // The viewport may have changed monitor since the global update in UpdateViewportsNewFrame()
15645
    // Either a SetNextWindowPos() call in the current frame or a SetWindowPos() call in the previous frame may have this effect.
15646
0
    if (viewport_rect_changed)
15647
0
        UpdateViewportPlatformMonitor(window->Viewport);
15648
15649
    // Update common viewport flags
15650
0
    const ImGuiViewportFlags viewport_flags_to_clear = ImGuiViewportFlags_TopMost | ImGuiViewportFlags_NoTaskBarIcon | ImGuiViewportFlags_NoDecoration | ImGuiViewportFlags_NoRendererClear;
15651
0
    ImGuiViewportFlags viewport_flags = window->Viewport->Flags & ~viewport_flags_to_clear;
15652
0
    ImGuiWindowFlags window_flags = window->Flags;
15653
0
    const bool is_modal = (window_flags & ImGuiWindowFlags_Modal) != 0;
15654
0
    const bool is_short_lived_floating_window = (window_flags & (ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) != 0;
15655
0
    if (window_flags & ImGuiWindowFlags_Tooltip)
15656
0
        viewport_flags |= ImGuiViewportFlags_TopMost;
15657
0
    if ((g.IO.ConfigViewportsNoTaskBarIcon || is_short_lived_floating_window) && !is_modal)
15658
0
        viewport_flags |= ImGuiViewportFlags_NoTaskBarIcon;
15659
0
    if (g.IO.ConfigViewportsNoDecoration || is_short_lived_floating_window)
15660
0
        viewport_flags |= ImGuiViewportFlags_NoDecoration;
15661
15662
    // Not correct to set modal as topmost because:
15663
    // - Because other popups can be stacked above a modal (e.g. combo box in a modal)
15664
    // - ImGuiViewportFlags_TopMost is currently handled different in backends: in Win32 it is "appear top most" whereas in GLFW and SDL it is "stay topmost"
15665
    //if (flags & ImGuiWindowFlags_Modal)
15666
    //    viewport_flags |= ImGuiViewportFlags_TopMost;
15667
15668
    // For popups and menus that may be protruding out of their parent viewport, we enable _NoFocusOnClick so that clicking on them
15669
    // won't steal the OS focus away from their parent window (which may be reflected in OS the title bar decoration).
15670
    // Setting _NoFocusOnClick would technically prevent us from bringing back to front in case they are being covered by an OS window from a different app,
15671
    // but it shouldn't be much of a problem considering those are already popups that are closed when clicking elsewhere.
15672
0
    if (is_short_lived_floating_window && !is_modal)
15673
0
        viewport_flags |= ImGuiViewportFlags_NoFocusOnAppearing | ImGuiViewportFlags_NoFocusOnClick;
15674
15675
    // We can overwrite viewport flags using ImGuiWindowClass (advanced users)
15676
0
    if (window->WindowClass.ViewportFlagsOverrideSet)
15677
0
        viewport_flags |= window->WindowClass.ViewportFlagsOverrideSet;
15678
0
    if (window->WindowClass.ViewportFlagsOverrideClear)
15679
0
        viewport_flags &= ~window->WindowClass.ViewportFlagsOverrideClear;
15680
15681
    // We can also tell the backend that clearing the platform window won't be necessary,
15682
    // as our window background is filling the viewport and we have disabled BgAlpha.
15683
    // FIXME: Work on support for per-viewport transparency (#2766)
15684
0
    if (!(window_flags & ImGuiWindowFlags_NoBackground))
15685
0
        viewport_flags |= ImGuiViewportFlags_NoRendererClear;
15686
15687
0
    window->Viewport->Flags = viewport_flags;
15688
15689
    // Update parent viewport ID
15690
    // (the !IsFallbackWindow test mimic the one done in WindowSelectViewport())
15691
0
    if (window->WindowClass.ParentViewportId != (ImGuiID)-1)
15692
0
        window->Viewport->ParentViewportId = window->WindowClass.ParentViewportId;
15693
0
    else if ((window_flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && parent_window_in_stack && (!parent_window_in_stack->IsFallbackWindow || parent_window_in_stack->WasActive))
15694
0
        window->Viewport->ParentViewportId = parent_window_in_stack->Viewport->ID;
15695
0
    else
15696
0
        window->Viewport->ParentViewportId = g.IO.ConfigViewportsNoDefaultParent ? 0 : IMGUI_VIEWPORT_DEFAULT_ID;
15697
0
}
15698
15699
// Called by user at the end of the main loop, after EndFrame()
15700
// This will handle the creation/update of all OS windows via function defined in the ImGuiPlatformIO api.
15701
void ImGui::UpdatePlatformWindows()
15702
0
{
15703
0
    ImGuiContext& g = *GImGui;
15704
0
    IM_ASSERT(g.FrameCountEnded == g.FrameCount && "Forgot to call Render() or EndFrame() before UpdatePlatformWindows()?");
15705
0
    IM_ASSERT(g.FrameCountPlatformEnded < g.FrameCount);
15706
0
    g.FrameCountPlatformEnded = g.FrameCount;
15707
0
    if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
15708
0
        return;
15709
15710
    // Create/resize/destroy platform windows to match each active viewport.
15711
    // Skip the main viewport (index 0), which is always fully handled by the application!
15712
0
    for (int i = 1; i < g.Viewports.Size; i++)
15713
0
    {
15714
0
        ImGuiViewportP* viewport = g.Viewports[i];
15715
15716
        // Destroy platform window if the viewport hasn't been submitted or if it is hosting a hidden window
15717
        // (the implicit/fallback Debug##Default window will be registering its viewport then be disabled, causing a dummy DestroyPlatformWindow to be made each frame)
15718
0
        bool destroy_platform_window = false;
15719
0
        destroy_platform_window |= (viewport->LastFrameActive < g.FrameCount - 1);
15720
0
        destroy_platform_window |= (viewport->Window && !IsWindowActiveAndVisible(viewport->Window));
15721
0
        if (destroy_platform_window)
15722
0
        {
15723
0
            DestroyPlatformWindow(viewport);
15724
0
            continue;
15725
0
        }
15726
15727
        // New windows that appears directly in a new viewport won't always have a size on their first frame
15728
0
        if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0 || viewport->Size.y <= 0)
15729
0
            continue;
15730
15731
        // Create window
15732
0
        const bool is_new_platform_window = (viewport->PlatformWindowCreated == false);
15733
0
        if (is_new_platform_window)
15734
0
        {
15735
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Create Platform Window %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
15736
0
            g.PlatformIO.Platform_CreateWindow(viewport);
15737
0
            if (g.PlatformIO.Renderer_CreateWindow != NULL)
15738
0
                g.PlatformIO.Renderer_CreateWindow(viewport);
15739
0
            g.PlatformWindowsCreatedCount++;
15740
0
            viewport->LastNameHash = 0;
15741
0
            viewport->LastPlatformPos = viewport->LastPlatformSize = ImVec2(FLT_MAX, FLT_MAX); // By clearing those we'll enforce a call to Platform_SetWindowPos/Size below, before Platform_ShowWindow (FIXME: Is that necessary?)
15742
0
            viewport->LastRendererSize = viewport->Size;                                       // We don't need to call Renderer_SetWindowSize() as it is expected Renderer_CreateWindow() already did it.
15743
0
            viewport->PlatformWindowCreated = true;
15744
0
        }
15745
15746
        // Apply Position and Size (from ImGui to Platform/Renderer backends)
15747
0
        if ((viewport->LastPlatformPos.x != viewport->Pos.x || viewport->LastPlatformPos.y != viewport->Pos.y) && !viewport->PlatformRequestMove)
15748
0
            g.PlatformIO.Platform_SetWindowPos(viewport, viewport->Pos);
15749
0
        if ((viewport->LastPlatformSize.x != viewport->Size.x || viewport->LastPlatformSize.y != viewport->Size.y) && !viewport->PlatformRequestResize)
15750
0
            g.PlatformIO.Platform_SetWindowSize(viewport, viewport->Size);
15751
0
        if ((viewport->LastRendererSize.x != viewport->Size.x || viewport->LastRendererSize.y != viewport->Size.y) && g.PlatformIO.Renderer_SetWindowSize)
15752
0
            g.PlatformIO.Renderer_SetWindowSize(viewport, viewport->Size);
15753
0
        viewport->LastPlatformPos = viewport->Pos;
15754
0
        viewport->LastPlatformSize = viewport->LastRendererSize = viewport->Size;
15755
15756
        // Update title bar (if it changed)
15757
0
        if (ImGuiWindow* window_for_title = GetWindowForTitleDisplay(viewport->Window))
15758
0
        {
15759
0
            const char* title_begin = window_for_title->Name;
15760
0
            char* title_end = (char*)(intptr_t)FindRenderedTextEnd(title_begin);
15761
0
            const ImGuiID title_hash = ImHashStr(title_begin, title_end - title_begin);
15762
0
            if (viewport->LastNameHash != title_hash)
15763
0
            {
15764
0
                char title_end_backup_c = *title_end;
15765
0
                *title_end = 0; // Cut existing buffer short instead of doing an alloc/free, no small gain.
15766
0
                g.PlatformIO.Platform_SetWindowTitle(viewport, title_begin);
15767
0
                *title_end = title_end_backup_c;
15768
0
                viewport->LastNameHash = title_hash;
15769
0
            }
15770
0
        }
15771
15772
        // Update alpha (if it changed)
15773
0
        if (viewport->LastAlpha != viewport->Alpha && g.PlatformIO.Platform_SetWindowAlpha)
15774
0
            g.PlatformIO.Platform_SetWindowAlpha(viewport, viewport->Alpha);
15775
0
        viewport->LastAlpha = viewport->Alpha;
15776
15777
        // Optional, general purpose call to allow the backend to perform general book-keeping even if things haven't changed.
15778
0
        if (g.PlatformIO.Platform_UpdateWindow)
15779
0
            g.PlatformIO.Platform_UpdateWindow(viewport);
15780
15781
0
        if (is_new_platform_window)
15782
0
        {
15783
            // On startup ensure new platform window don't steal focus (give it a few frames, as nested contents may lead to viewport being created a few frames late)
15784
0
            if (g.FrameCount < 3)
15785
0
                viewport->Flags |= ImGuiViewportFlags_NoFocusOnAppearing;
15786
15787
            // Show window
15788
0
            g.PlatformIO.Platform_ShowWindow(viewport);
15789
15790
            // Even without focus, we assume the window becomes front-most.
15791
            // This is useful for our platform z-order heuristic when io.MouseHoveredViewport is not available.
15792
0
            if (viewport->LastFocusedStampCount != g.ViewportFocusedStampCount)
15793
0
                viewport->LastFocusedStampCount = ++g.ViewportFocusedStampCount;
15794
0
        }
15795
15796
        // Clear request flags
15797
0
        viewport->ClearRequestFlags();
15798
0
    }
15799
0
}
15800
15801
// This is a default/basic function for performing the rendering/swap of multiple Platform Windows.
15802
// Custom renderers may prefer to not call this function at all, and instead iterate the publicly exposed platform data and handle rendering/sync themselves.
15803
// The Render/Swap functions stored in ImGuiPlatformIO are merely here to allow for this helper to exist, but you can do it yourself:
15804
//
15805
//    ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
15806
//    for (int i = 1; i < platform_io.Viewports.Size; i++)
15807
//        if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
15808
//            MyRenderFunction(platform_io.Viewports[i], my_args);
15809
//    for (int i = 1; i < platform_io.Viewports.Size; i++)
15810
//        if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
15811
//            MySwapBufferFunction(platform_io.Viewports[i], my_args);
15812
//
15813
void ImGui::RenderPlatformWindowsDefault(void* platform_render_arg, void* renderer_render_arg)
15814
0
{
15815
    // Skip the main viewport (index 0), which is always fully handled by the application!
15816
0
    ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
15817
0
    for (int i = 1; i < platform_io.Viewports.Size; i++)
15818
0
    {
15819
0
        ImGuiViewport* viewport = platform_io.Viewports[i];
15820
0
        if (viewport->Flags & ImGuiViewportFlags_IsMinimized)
15821
0
            continue;
15822
0
        if (platform_io.Platform_RenderWindow) platform_io.Platform_RenderWindow(viewport, platform_render_arg);
15823
0
        if (platform_io.Renderer_RenderWindow) platform_io.Renderer_RenderWindow(viewport, renderer_render_arg);
15824
0
    }
15825
0
    for (int i = 1; i < platform_io.Viewports.Size; i++)
15826
0
    {
15827
0
        ImGuiViewport* viewport = platform_io.Viewports[i];
15828
0
        if (viewport->Flags & ImGuiViewportFlags_IsMinimized)
15829
0
            continue;
15830
0
        if (platform_io.Platform_SwapBuffers) platform_io.Platform_SwapBuffers(viewport, platform_render_arg);
15831
0
        if (platform_io.Renderer_SwapBuffers) platform_io.Renderer_SwapBuffers(viewport, renderer_render_arg);
15832
0
    }
15833
0
}
15834
15835
static int ImGui::FindPlatformMonitorForPos(const ImVec2& pos)
15836
0
{
15837
0
    ImGuiContext& g = *GImGui;
15838
0
    for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++)
15839
0
    {
15840
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
15841
0
        if (ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize).Contains(pos))
15842
0
            return monitor_n;
15843
0
    }
15844
0
    return -1;
15845
0
}
15846
15847
// Search for the monitor with the largest intersection area with the given rectangle
15848
// We generally try to avoid searching loops but the monitor count should be very small here
15849
// FIXME-OPT: We could test the last monitor used for that viewport first, and early
15850
static int ImGui::FindPlatformMonitorForRect(const ImRect& rect)
15851
84.9k
{
15852
84.9k
    ImGuiContext& g = *GImGui;
15853
15854
84.9k
    const int monitor_count = g.PlatformIO.Monitors.Size;
15855
84.9k
    if (monitor_count <= 1)
15856
84.9k
        return monitor_count - 1;
15857
15858
    // Use a minimum threshold of 1.0f so a zero-sized rect won't false positive, and will still find the correct monitor given its position.
15859
    // This is necessary for tooltips which always resize down to zero at first.
15860
0
    const float surface_threshold = ImMax(rect.GetWidth() * rect.GetHeight() * 0.5f, 1.0f);
15861
0
    int best_monitor_n = -1;
15862
0
    float best_monitor_surface = 0.001f;
15863
15864
0
    for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size && best_monitor_surface < surface_threshold; monitor_n++)
15865
0
    {
15866
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
15867
0
        const ImRect monitor_rect = ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize);
15868
0
        if (monitor_rect.Contains(rect))
15869
0
            return monitor_n;
15870
0
        ImRect overlapping_rect = rect;
15871
0
        overlapping_rect.ClipWithFull(monitor_rect);
15872
0
        float overlapping_surface = overlapping_rect.GetWidth() * overlapping_rect.GetHeight();
15873
0
        if (overlapping_surface < best_monitor_surface)
15874
0
            continue;
15875
0
        best_monitor_surface = overlapping_surface;
15876
0
        best_monitor_n = monitor_n;
15877
0
    }
15878
0
    return best_monitor_n;
15879
0
}
15880
15881
// Update monitor from viewport rectangle (we'll use this info to clamp windows and save windows lost in a removed monitor)
15882
static void ImGui::UpdateViewportPlatformMonitor(ImGuiViewportP* viewport)
15883
84.9k
{
15884
84.9k
    viewport->PlatformMonitor = (short)FindPlatformMonitorForRect(viewport->GetMainRect());
15885
84.9k
}
15886
15887
// Return value is always != NULL, but don't hold on it across frames.
15888
const ImGuiPlatformMonitor* ImGui::GetViewportPlatformMonitor(ImGuiViewport* viewport_p)
15889
0
{
15890
0
    ImGuiContext& g = *GImGui;
15891
0
    ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)viewport_p;
15892
0
    int monitor_idx = viewport->PlatformMonitor;
15893
0
    if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
15894
0
        return &g.PlatformIO.Monitors[monitor_idx];
15895
0
    return &g.FallbackMonitor;
15896
0
}
15897
15898
void ImGui::DestroyPlatformWindow(ImGuiViewportP* viewport)
15899
0
{
15900
0
    ImGuiContext& g = *GImGui;
15901
0
    if (viewport->PlatformWindowCreated)
15902
0
    {
15903
0
        IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Destroy Platform Window %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
15904
0
        if (g.PlatformIO.Renderer_DestroyWindow)
15905
0
            g.PlatformIO.Renderer_DestroyWindow(viewport);
15906
0
        if (g.PlatformIO.Platform_DestroyWindow)
15907
0
            g.PlatformIO.Platform_DestroyWindow(viewport);
15908
0
        IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL);
15909
15910
        // Don't clear PlatformWindowCreated for the main viewport, as we initially set that up to true in Initialize()
15911
        // The righter way may be to leave it to the backend to set this flag all-together, and made the flag public.
15912
0
        if (viewport->ID != IMGUI_VIEWPORT_DEFAULT_ID)
15913
0
            viewport->PlatformWindowCreated = false;
15914
0
    }
15915
0
    else
15916
0
    {
15917
0
        IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL && viewport->PlatformHandle == NULL);
15918
0
    }
15919
0
    viewport->RendererUserData = viewport->PlatformUserData = viewport->PlatformHandle = NULL;
15920
0
    viewport->ClearRequestFlags();
15921
0
}
15922
15923
void ImGui::DestroyPlatformWindows()
15924
0
{
15925
    // We call the destroy window on every viewport (including the main viewport, index 0) to give a chance to the backend
15926
    // to clear any data they may have stored in e.g. PlatformUserData, RendererUserData.
15927
    // It is convenient for the platform backend code to store something in the main viewport, in order for e.g. the mouse handling
15928
    // code to operator a consistent manner.
15929
    // It is expected that the backend can handle calls to Renderer_DestroyWindow/Platform_DestroyWindow without
15930
    // crashing if it doesn't have data stored.
15931
0
    ImGuiContext& g = *GImGui;
15932
0
    for (ImGuiViewportP* viewport : g.Viewports)
15933
0
        DestroyPlatformWindow(viewport);
15934
0
}
15935
15936
15937
//-----------------------------------------------------------------------------
15938
// [SECTION] DOCKING
15939
//-----------------------------------------------------------------------------
15940
// Docking: Internal Types
15941
// Docking: Forward Declarations
15942
// Docking: ImGuiDockContext
15943
// Docking: ImGuiDockContext Docking/Undocking functions
15944
// Docking: ImGuiDockNode
15945
// Docking: ImGuiDockNode Tree manipulation functions
15946
// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
15947
// Docking: Builder Functions
15948
// Docking: Begin/End Support Functions (called from Begin/End)
15949
// Docking: Settings
15950
//-----------------------------------------------------------------------------
15951
15952
//-----------------------------------------------------------------------------
15953
// Typical Docking call flow: (root level is generally public API):
15954
//-----------------------------------------------------------------------------
15955
// - NewFrame()                               new dear imgui frame
15956
//    | DockContextNewFrameUpdateUndocking()  - process queued undocking requests
15957
//    | - DockContextProcessUndockWindow()    - process one window undocking request
15958
//    | - DockContextProcessUndockNode()      - process one whole node undocking request
15959
//    | DockContextNewFrameUpdateUndocking()  - process queue docking requests, create floating dock nodes
15960
//    | - update g.HoveredDockNode            - [debug] update node hovered by mouse
15961
//    | - DockContextProcessDock()            - process one docking request
15962
//    | - DockNodeUpdate()
15963
//    |   - DockNodeUpdateForRootNode()
15964
//    |     - DockNodeUpdateFlagsAndCollapse()
15965
//    |     - DockNodeFindInfo()
15966
//    |   - destroy unused node or tab bar
15967
//    |   - create dock node host window
15968
//    |      - Begin() etc.
15969
//    |   - DockNodeStartMouseMovingWindow()
15970
//    |   - DockNodeTreeUpdatePosSize()
15971
//    |   - DockNodeTreeUpdateSplitter()
15972
//    |   - draw node background
15973
//    |   - DockNodeUpdateTabBar()            - create/update tab bar for a docking node
15974
//    |     - DockNodeAddTabBar()
15975
//    |     - DockNodeWindowMenuUpdate()
15976
//    |     - DockNodeCalcTabBarLayout()
15977
//    |     - BeginTabBarEx()
15978
//    |     - TabItemEx() calls
15979
//    |     - EndTabBar()
15980
//    |   - BeginDockableDragDropTarget()
15981
//    |      - DockNodeUpdate()               - recurse into child nodes...
15982
//-----------------------------------------------------------------------------
15983
// - DockSpace()                              user submit a dockspace into a window
15984
//    | Begin(Child)                          - create a child window
15985
//    | DockNodeUpdate()                      - call main dock node update function
15986
//    | End(Child)
15987
//    | ItemSize()
15988
//-----------------------------------------------------------------------------
15989
// - Begin()
15990
//    | BeginDocked()
15991
//    | BeginDockableDragDropSource()
15992
//    | BeginDockableDragDropTarget()
15993
//    | - DockNodePreviewDockRender()
15994
//-----------------------------------------------------------------------------
15995
// - EndFrame()
15996
//    | DockContextEndFrame()
15997
//-----------------------------------------------------------------------------
15998
15999
//-----------------------------------------------------------------------------
16000
// Docking: Internal Types
16001
//-----------------------------------------------------------------------------
16002
// - ImGuiDockRequestType
16003
// - ImGuiDockRequest
16004
// - ImGuiDockPreviewData
16005
// - ImGuiDockNodeSettings
16006
// - ImGuiDockContext
16007
//-----------------------------------------------------------------------------
16008
16009
enum ImGuiDockRequestType
16010
{
16011
    ImGuiDockRequestType_None = 0,
16012
    ImGuiDockRequestType_Dock,
16013
    ImGuiDockRequestType_Undock,
16014
    ImGuiDockRequestType_Split                  // Split is the same as Dock but without a DockPayload
16015
};
16016
16017
struct ImGuiDockRequest
16018
{
16019
    ImGuiDockRequestType    Type;
16020
    ImGuiWindow*            DockTargetWindow;   // Destination/Target Window to dock into (may be a loose window or a DockNode, might be NULL in which case DockTargetNode cannot be NULL)
16021
    ImGuiDockNode*          DockTargetNode;     // Destination/Target Node to dock into
16022
    ImGuiWindow*            DockPayload;        // Source/Payload window to dock (may be a loose window or a DockNode), [Optional]
16023
    ImGuiDir                DockSplitDir;
16024
    float                   DockSplitRatio;
16025
    bool                    DockSplitOuter;
16026
    ImGuiWindow*            UndockTargetWindow;
16027
    ImGuiDockNode*          UndockTargetNode;
16028
16029
    ImGuiDockRequest()
16030
0
    {
16031
0
        Type = ImGuiDockRequestType_None;
16032
0
        DockTargetWindow = DockPayload = UndockTargetWindow = NULL;
16033
0
        DockTargetNode = UndockTargetNode = NULL;
16034
0
        DockSplitDir = ImGuiDir_None;
16035
0
        DockSplitRatio = 0.5f;
16036
0
        DockSplitOuter = false;
16037
0
    }
16038
};
16039
16040
struct ImGuiDockPreviewData
16041
{
16042
    ImGuiDockNode   FutureNode;
16043
    bool            IsDropAllowed;
16044
    bool            IsCenterAvailable;
16045
    bool            IsSidesAvailable;           // Hold your breath, grammar freaks..
16046
    bool            IsSplitDirExplicit;         // Set when hovered the drop rect (vs. implicit SplitDir==None when hovered the window)
16047
    ImGuiDockNode*  SplitNode;
16048
    ImGuiDir        SplitDir;
16049
    float           SplitRatio;
16050
    ImRect          DropRectsDraw[ImGuiDir_COUNT + 1];  // May be slightly different from hit-testing drop rects used in DockNodeCalcDropRects()
16051
16052
0
    ImGuiDockPreviewData() : FutureNode(0) { IsDropAllowed = IsCenterAvailable = IsSidesAvailable = IsSplitDirExplicit = false; SplitNode = NULL; SplitDir = ImGuiDir_None; SplitRatio = 0.f; for (int n = 0; n < IM_ARRAYSIZE(DropRectsDraw); n++) DropRectsDraw[n] = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX); }
16053
};
16054
16055
// Persistent Settings data, stored contiguously in SettingsNodes (sizeof() ~32 bytes)
16056
struct ImGuiDockNodeSettings
16057
{
16058
    ImGuiID             ID;
16059
    ImGuiID             ParentNodeId;
16060
    ImGuiID             ParentWindowId;
16061
    ImGuiID             SelectedTabId;
16062
    signed char         SplitAxis;
16063
    char                Depth;
16064
    ImGuiDockNodeFlags  Flags;                  // NB: We save individual flags one by one in ascii format (ImGuiDockNodeFlags_SavedFlagsMask_)
16065
    ImVec2ih            Pos;
16066
    ImVec2ih            Size;
16067
    ImVec2ih            SizeRef;
16068
0
    ImGuiDockNodeSettings() { memset(this, 0, sizeof(*this)); SplitAxis = ImGuiAxis_None; }
16069
};
16070
16071
//-----------------------------------------------------------------------------
16072
// Docking: Forward Declarations
16073
//-----------------------------------------------------------------------------
16074
16075
namespace ImGui
16076
{
16077
    // ImGuiDockContext
16078
    static ImGuiDockNode*   DockContextAddNode(ImGuiContext* ctx, ImGuiID id);
16079
    static void             DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node);
16080
    static void             DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node);
16081
    static void             DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req);
16082
    static void             DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx);
16083
    static ImGuiDockNode*   DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window);
16084
    static void             DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count);
16085
    static void             DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id);                            // Use root_id==0 to add all
16086
16087
    // ImGuiDockNode
16088
    static void             DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar);
16089
    static void             DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
16090
    static void             DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
16091
    static ImGuiWindow*     DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id);
16092
    static void             DockNodeApplyPosSizeToWindows(ImGuiDockNode* node);
16093
    static void             DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id);
16094
    static void             DockNodeHideHostWindow(ImGuiDockNode* node);
16095
    static void             DockNodeUpdate(ImGuiDockNode* node);
16096
    static void             DockNodeUpdateForRootNode(ImGuiDockNode* node);
16097
    static void             DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node);
16098
    static void             DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node);
16099
    static void             DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window);
16100
    static void             DockNodeAddTabBar(ImGuiDockNode* node);
16101
    static void             DockNodeRemoveTabBar(ImGuiDockNode* node);
16102
    static void             DockNodeWindowMenuUpdate(ImGuiDockNode* node, ImGuiTabBar* tab_bar);
16103
    static void             DockNodeUpdateVisibleFlag(ImGuiDockNode* node);
16104
    static void             DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window);
16105
    static bool             DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* payload_window);
16106
    static void             DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDockPreviewData* preview_data, bool is_explicit_target, bool is_outer_docking);
16107
    static void             DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, const ImGuiDockPreviewData* preview_data);
16108
    static void             DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos, ImVec2* out_close_button_pos);
16109
    static void             DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired);
16110
    static bool             DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_draw, bool outer_docking, ImVec2* test_mouse_pos);
16111
0
    static const char*      DockNodeGetHostWindowTitle(ImGuiDockNode* node, char* buf, int buf_size) { ImFormatString(buf, buf_size, "##DockNode_%02X", node->ID); return buf; }
16112
    static int              DockNodeGetTabOrder(ImGuiWindow* window);
16113
16114
    // ImGuiDockNode tree manipulations
16115
    static void             DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_first_child, float split_ratio, ImGuiDockNode* new_node);
16116
    static void             DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child);
16117
    static void             DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node = NULL);
16118
    static void             DockNodeTreeUpdateSplitter(ImGuiDockNode* node);
16119
    static ImGuiDockNode*   DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos);
16120
    static ImGuiDockNode*   DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node);
16121
16122
    // Settings
16123
    static void             DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id);
16124
    static void             DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count);
16125
    static ImGuiDockNodeSettings*   DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID node_id);
16126
    static void             DockSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
16127
    static void             DockSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
16128
    static void*            DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
16129
    static void             DockSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
16130
    static void             DockSettingsHandler_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf);
16131
}
16132
16133
//-----------------------------------------------------------------------------
16134
// Docking: ImGuiDockContext
16135
//-----------------------------------------------------------------------------
16136
// The lifetime model is different from the one of regular windows: we always create a ImGuiDockNode for each ImGuiDockNodeSettings,
16137
// or we always hold the entire docking node tree. Nodes are frequently hidden, e.g. if the window(s) or child nodes they host are not active.
16138
// At boot time only, we run a simple GC to remove nodes that have no references.
16139
// Because dock node settings (which are small, contiguous structures) are always mirrored by their corresponding dock nodes (more complete structures),
16140
// we can also very easily recreate the nodes from scratch given the settings data (this is what DockContextRebuild() does).
16141
// This is convenient as docking reconfiguration can be implemented by mostly poking at the simpler settings data.
16142
//-----------------------------------------------------------------------------
16143
// - DockContextInitialize()
16144
// - DockContextShutdown()
16145
// - DockContextClearNodes()
16146
// - DockContextRebuildNodes()
16147
// - DockContextNewFrameUpdateUndocking()
16148
// - DockContextNewFrameUpdateDocking()
16149
// - DockContextEndFrame()
16150
// - DockContextFindNodeByID()
16151
// - DockContextBindNodeToWindow()
16152
// - DockContextGenNodeID()
16153
// - DockContextAddNode()
16154
// - DockContextRemoveNode()
16155
// - ImGuiDockContextPruneNodeData
16156
// - DockContextPruneUnusedSettingsNodes()
16157
// - DockContextBuildNodesFromSettings()
16158
// - DockContextBuildAddWindowsToNodes()
16159
//-----------------------------------------------------------------------------
16160
16161
void ImGui::DockContextInitialize(ImGuiContext* ctx)
16162
1
{
16163
1
    ImGuiContext& g = *ctx;
16164
16165
    // Add .ini handle for persistent docking data
16166
1
    ImGuiSettingsHandler ini_handler;
16167
1
    ini_handler.TypeName = "Docking";
16168
1
    ini_handler.TypeHash = ImHashStr("Docking");
16169
1
    ini_handler.ClearAllFn = DockSettingsHandler_ClearAll;
16170
1
    ini_handler.ReadInitFn = DockSettingsHandler_ClearAll; // Also clear on read
16171
1
    ini_handler.ReadOpenFn = DockSettingsHandler_ReadOpen;
16172
1
    ini_handler.ReadLineFn = DockSettingsHandler_ReadLine;
16173
1
    ini_handler.ApplyAllFn = DockSettingsHandler_ApplyAll;
16174
1
    ini_handler.WriteAllFn = DockSettingsHandler_WriteAll;
16175
1
    g.SettingsHandlers.push_back(ini_handler);
16176
16177
1
    g.DockNodeWindowMenuHandler = &DockNodeWindowMenuHandler_Default;
16178
1
}
16179
16180
void ImGui::DockContextShutdown(ImGuiContext* ctx)
16181
0
{
16182
0
    ImGuiDockContext* dc = &ctx->DockContext;
16183
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
16184
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
16185
0
            IM_DELETE(node);
16186
0
}
16187
16188
void ImGui::DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_settings_refs)
16189
0
{
16190
0
    IM_UNUSED(ctx);
16191
0
    IM_ASSERT(ctx == GImGui);
16192
0
    DockBuilderRemoveNodeDockedWindows(root_id, clear_settings_refs);
16193
0
    DockBuilderRemoveNodeChildNodes(root_id);
16194
0
}
16195
16196
// [DEBUG] This function also acts as a defacto test to make sure we can rebuild from scratch without a glitch
16197
// (Different from DockSettingsHandler_ClearAll() + DockSettingsHandler_ApplyAll() because this reuses current settings!)
16198
void ImGui::DockContextRebuildNodes(ImGuiContext* ctx)
16199
0
{
16200
0
    ImGuiContext& g = *ctx;
16201
0
    ImGuiDockContext* dc = &ctx->DockContext;
16202
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRebuildNodes\n");
16203
0
    SaveIniSettingsToMemory();
16204
0
    ImGuiID root_id = 0; // Rebuild all
16205
0
    DockContextClearNodes(ctx, root_id, false);
16206
0
    DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size);
16207
0
    DockContextBuildAddWindowsToNodes(ctx, root_id);
16208
0
}
16209
16210
// Docking context update function, called by NewFrame()
16211
void ImGui::DockContextNewFrameUpdateUndocking(ImGuiContext* ctx)
16212
84.9k
{
16213
84.9k
    ImGuiContext& g = *ctx;
16214
84.9k
    ImGuiDockContext* dc = &ctx->DockContext;
16215
84.9k
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
16216
0
    {
16217
0
        if (dc->Nodes.Data.Size > 0 || dc->Requests.Size > 0)
16218
0
            DockContextClearNodes(ctx, 0, true);
16219
0
        return;
16220
0
    }
16221
16222
    // Setting NoSplit at runtime merges all nodes
16223
84.9k
    if (g.IO.ConfigDockingNoSplit)
16224
0
        for (int n = 0; n < dc->Nodes.Data.Size; n++)
16225
0
            if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
16226
0
                if (node->IsRootNode() && node->IsSplitNode())
16227
0
                {
16228
0
                    DockBuilderRemoveNodeChildNodes(node->ID);
16229
                    //dc->WantFullRebuild = true;
16230
0
                }
16231
16232
    // Process full rebuild
16233
#if 0
16234
    if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_C)))
16235
        dc->WantFullRebuild = true;
16236
#endif
16237
84.9k
    if (dc->WantFullRebuild)
16238
0
    {
16239
0
        DockContextRebuildNodes(ctx);
16240
0
        dc->WantFullRebuild = false;
16241
0
    }
16242
16243
    // Process Undocking requests (we need to process them _before_ the UpdateMouseMovingWindowNewFrame call in NewFrame)
16244
84.9k
    for (ImGuiDockRequest& req : dc->Requests)
16245
0
    {
16246
0
        if (req.Type == ImGuiDockRequestType_Undock && req.UndockTargetWindow)
16247
0
            DockContextProcessUndockWindow(ctx, req.UndockTargetWindow);
16248
0
        else if (req.Type == ImGuiDockRequestType_Undock && req.UndockTargetNode)
16249
0
            DockContextProcessUndockNode(ctx, req.UndockTargetNode);
16250
0
    }
16251
84.9k
}
16252
16253
// Docking context update function, called by NewFrame()
16254
void ImGui::DockContextNewFrameUpdateDocking(ImGuiContext* ctx)
16255
84.9k
{
16256
84.9k
    ImGuiContext& g = *ctx;
16257
84.9k
    ImGuiDockContext* dc = &ctx->DockContext;
16258
84.9k
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
16259
0
        return;
16260
16261
    // [DEBUG] Store hovered dock node.
16262
    // We could in theory use DockNodeTreeFindVisibleNodeByPos() on the root host dock node, but using ->DockNode is a good shortcut.
16263
    // Note this is mostly a debug thing and isn't actually used for docking target, because docking involve more detailed filtering.
16264
84.9k
    g.DebugHoveredDockNode = NULL;
16265
84.9k
    if (ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow)
16266
328
    {
16267
328
        if (hovered_window->DockNodeAsHost)
16268
0
            g.DebugHoveredDockNode = DockNodeTreeFindVisibleNodeByPos(hovered_window->DockNodeAsHost, g.IO.MousePos);
16269
328
        else if (hovered_window->RootWindow->DockNode)
16270
0
            g.DebugHoveredDockNode = hovered_window->RootWindow->DockNode;
16271
328
    }
16272
16273
    // Process Docking requests
16274
84.9k
    for (ImGuiDockRequest& req : dc->Requests)
16275
0
        if (req.Type == ImGuiDockRequestType_Dock)
16276
0
            DockContextProcessDock(ctx, &req);
16277
84.9k
    dc->Requests.resize(0);
16278
16279
    // Create windows for each automatic docking nodes
16280
    // We can have NULL pointers when we delete nodes, but because ID are recycled this should amortize nicely (and our node count will never be very high)
16281
84.9k
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
16282
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
16283
0
            if (node->IsFloatingNode())
16284
0
                DockNodeUpdate(node);
16285
84.9k
}
16286
16287
void ImGui::DockContextEndFrame(ImGuiContext* ctx)
16288
84.9k
{
16289
    // Draw backgrounds of node missing their window
16290
84.9k
    ImGuiContext& g = *ctx;
16291
84.9k
    ImGuiDockContext* dc = &g.DockContext;
16292
84.9k
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
16293
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
16294
0
            if (node->LastFrameActive == g.FrameCount && node->IsVisible && node->HostWindow && node->IsLeafNode() && !node->IsBgDrawnThisFrame)
16295
0
            {
16296
0
                ImRect bg_rect(node->Pos + ImVec2(0.0f, GetFrameHeight()), node->Pos + node->Size);
16297
0
                ImDrawFlags bg_rounding_flags = CalcRoundingFlagsForRectInRect(bg_rect, node->HostWindow->Rect(), g.Style.DockingSeparatorSize);
16298
0
                node->HostWindow->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
16299
0
                node->HostWindow->DrawList->AddRectFilled(bg_rect.Min, bg_rect.Max, node->LastBgColor, node->HostWindow->WindowRounding, bg_rounding_flags);
16300
0
            }
16301
84.9k
}
16302
16303
ImGuiDockNode* ImGui::DockContextFindNodeByID(ImGuiContext* ctx, ImGuiID id)
16304
0
{
16305
0
    return (ImGuiDockNode*)ctx->DockContext.Nodes.GetVoidPtr(id);
16306
0
}
16307
16308
ImGuiID ImGui::DockContextGenNodeID(ImGuiContext* ctx)
16309
0
{
16310
    // Generate an ID for new node (the exact ID value doesn't matter as long as it is not already used)
16311
    // FIXME-OPT FIXME-DOCK: This is suboptimal, even if the node count is small enough not to be a worry.0
16312
    // We should poke in ctx->Nodes to find a suitable ID faster. Even more so trivial that ctx->Nodes lookup is already sorted.
16313
0
    ImGuiID id = 0x0001;
16314
0
    while (DockContextFindNodeByID(ctx, id) != NULL)
16315
0
        id++;
16316
0
    return id;
16317
0
}
16318
16319
static ImGuiDockNode* ImGui::DockContextAddNode(ImGuiContext* ctx, ImGuiID id)
16320
0
{
16321
    // Generate an ID for the new node (the exact ID value doesn't matter as long as it is not already used) and add the first window.
16322
0
    ImGuiContext& g = *ctx;
16323
0
    if (id == 0)
16324
0
        id = DockContextGenNodeID(ctx);
16325
0
    else
16326
0
        IM_ASSERT(DockContextFindNodeByID(ctx, id) == NULL);
16327
16328
    // We don't set node->LastFrameAlive on construction. Nodes are always created at all time to reflect .ini settings!
16329
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextAddNode 0x%08X\n", id);
16330
0
    ImGuiDockNode* node = IM_NEW(ImGuiDockNode)(id);
16331
0
    ctx->DockContext.Nodes.SetVoidPtr(node->ID, node);
16332
0
    return node;
16333
0
}
16334
16335
static void ImGui::DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node)
16336
0
{
16337
0
    ImGuiContext& g = *ctx;
16338
0
    ImGuiDockContext* dc = &ctx->DockContext;
16339
16340
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRemoveNode 0x%08X\n", node->ID);
16341
0
    IM_ASSERT(DockContextFindNodeByID(ctx, node->ID) == node);
16342
0
    IM_ASSERT(node->ChildNodes[0] == NULL && node->ChildNodes[1] == NULL);
16343
0
    IM_ASSERT(node->Windows.Size == 0);
16344
16345
0
    if (node->HostWindow)
16346
0
        node->HostWindow->DockNodeAsHost = NULL;
16347
16348
0
    ImGuiDockNode* parent_node = node->ParentNode;
16349
0
    const bool merge = (merge_sibling_into_parent_node && parent_node != NULL);
16350
0
    if (merge)
16351
0
    {
16352
0
        IM_ASSERT(parent_node->ChildNodes[0] == node || parent_node->ChildNodes[1] == node);
16353
0
        ImGuiDockNode* sibling_node = (parent_node->ChildNodes[0] == node ? parent_node->ChildNodes[1] : parent_node->ChildNodes[0]);
16354
0
        DockNodeTreeMerge(&g, parent_node, sibling_node);
16355
0
    }
16356
0
    else
16357
0
    {
16358
0
        for (int n = 0; parent_node && n < IM_ARRAYSIZE(parent_node->ChildNodes); n++)
16359
0
            if (parent_node->ChildNodes[n] == node)
16360
0
                node->ParentNode->ChildNodes[n] = NULL;
16361
0
        dc->Nodes.SetVoidPtr(node->ID, NULL);
16362
0
        IM_DELETE(node);
16363
0
    }
16364
0
}
16365
16366
static int IMGUI_CDECL DockNodeComparerDepthMostFirst(const void* lhs, const void* rhs)
16367
0
{
16368
0
    const ImGuiDockNode* a = *(const ImGuiDockNode* const*)lhs;
16369
0
    const ImGuiDockNode* b = *(const ImGuiDockNode* const*)rhs;
16370
0
    return ImGui::DockNodeGetDepth(b) - ImGui::DockNodeGetDepth(a);
16371
0
}
16372
16373
// Pre C++0x doesn't allow us to use a function-local type (without linkage) as template parameter, so we moved this here.
16374
struct ImGuiDockContextPruneNodeData
16375
{
16376
    int         CountWindows, CountChildWindows, CountChildNodes;
16377
    ImGuiID     RootId;
16378
0
    ImGuiDockContextPruneNodeData() { CountWindows = CountChildWindows = CountChildNodes = 0; RootId = 0; }
16379
};
16380
16381
// Garbage collect unused nodes (run once at init time)
16382
static void ImGui::DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx)
16383
0
{
16384
0
    ImGuiContext& g = *ctx;
16385
0
    ImGuiDockContext* dc = &ctx->DockContext;
16386
0
    IM_ASSERT(g.Windows.Size == 0);
16387
16388
0
    ImPool<ImGuiDockContextPruneNodeData> pool;
16389
0
    pool.Reserve(dc->NodesSettings.Size);
16390
16391
    // Count child nodes and compute RootID
16392
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
16393
0
    {
16394
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
16395
0
        ImGuiDockContextPruneNodeData* parent_data = settings->ParentNodeId ? pool.GetByKey(settings->ParentNodeId) : 0;
16396
0
        pool.GetOrAddByKey(settings->ID)->RootId = parent_data ? parent_data->RootId : settings->ID;
16397
0
        if (settings->ParentNodeId)
16398
0
            pool.GetOrAddByKey(settings->ParentNodeId)->CountChildNodes++;
16399
0
    }
16400
16401
    // Count reference to dock ids from dockspaces
16402
    // We track the 'auto-DockNode <- manual-Window <- manual-DockSpace' in order to avoid 'auto-DockNode' being ditched by DockContextPruneUnusedSettingsNodes()
16403
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
16404
0
    {
16405
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
16406
0
        if (settings->ParentWindowId != 0)
16407
0
            if (ImGuiWindowSettings* window_settings = FindWindowSettingsByID(settings->ParentWindowId))
16408
0
                if (window_settings->DockId)
16409
0
                    if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(window_settings->DockId))
16410
0
                        data->CountChildNodes++;
16411
0
    }
16412
16413
    // Count reference to dock ids from window settings
16414
    // We guard against the possibility of an invalid .ini file (RootID may point to a missing node)
16415
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
16416
0
        if (ImGuiID dock_id = settings->DockId)
16417
0
            if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(dock_id))
16418
0
            {
16419
0
                data->CountWindows++;
16420
0
                if (ImGuiDockContextPruneNodeData* data_root = (data->RootId == dock_id) ? data : pool.GetByKey(data->RootId))
16421
0
                    data_root->CountChildWindows++;
16422
0
            }
16423
16424
    // Prune
16425
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
16426
0
    {
16427
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
16428
0
        ImGuiDockContextPruneNodeData* data = pool.GetByKey(settings->ID);
16429
0
        if (data->CountWindows > 1)
16430
0
            continue;
16431
0
        ImGuiDockContextPruneNodeData* data_root = (data->RootId == settings->ID) ? data : pool.GetByKey(data->RootId);
16432
16433
0
        bool remove = false;
16434
0
        remove |= (data->CountWindows == 1 && settings->ParentNodeId == 0 && data->CountChildNodes == 0 && !(settings->Flags & ImGuiDockNodeFlags_CentralNode));  // Floating root node with only 1 window
16435
0
        remove |= (data->CountWindows == 0 && settings->ParentNodeId == 0 && data->CountChildNodes == 0); // Leaf nodes with 0 window
16436
0
        remove |= (data_root->CountChildWindows == 0);
16437
0
        if (remove)
16438
0
        {
16439
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextPruneUnusedSettingsNodes: Prune 0x%08X\n", settings->ID);
16440
0
            DockSettingsRemoveNodeReferences(&settings->ID, 1);
16441
0
            settings->ID = 0;
16442
0
        }
16443
0
    }
16444
0
}
16445
16446
static void ImGui::DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count)
16447
0
{
16448
    // Build nodes
16449
0
    for (int node_n = 0; node_n < node_settings_count; node_n++)
16450
0
    {
16451
0
        ImGuiDockNodeSettings* settings = &node_settings_array[node_n];
16452
0
        if (settings->ID == 0)
16453
0
            continue;
16454
0
        ImGuiDockNode* node = DockContextAddNode(ctx, settings->ID);
16455
0
        node->ParentNode = settings->ParentNodeId ? DockContextFindNodeByID(ctx, settings->ParentNodeId) : NULL;
16456
0
        node->Pos = ImVec2(settings->Pos.x, settings->Pos.y);
16457
0
        node->Size = ImVec2(settings->Size.x, settings->Size.y);
16458
0
        node->SizeRef = ImVec2(settings->SizeRef.x, settings->SizeRef.y);
16459
0
        node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_DockNode;
16460
0
        if (node->ParentNode && node->ParentNode->ChildNodes[0] == NULL)
16461
0
            node->ParentNode->ChildNodes[0] = node;
16462
0
        else if (node->ParentNode && node->ParentNode->ChildNodes[1] == NULL)
16463
0
            node->ParentNode->ChildNodes[1] = node;
16464
0
        node->SelectedTabId = settings->SelectedTabId;
16465
0
        node->SplitAxis = (ImGuiAxis)settings->SplitAxis;
16466
0
        node->SetLocalFlags(settings->Flags & ImGuiDockNodeFlags_SavedFlagsMask_);
16467
16468
        // Bind host window immediately if it already exist (in case of a rebuild)
16469
        // This is useful as the RootWindowForTitleBarHighlight links necessary to highlight the currently focused node requires node->HostWindow to be set.
16470
0
        char host_window_title[20];
16471
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
16472
0
        node->HostWindow = FindWindowByName(DockNodeGetHostWindowTitle(root_node, host_window_title, IM_ARRAYSIZE(host_window_title)));
16473
0
    }
16474
0
}
16475
16476
void ImGui::DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id)
16477
0
{
16478
    // Rebind all windows to nodes (they can also lazily rebind but we'll have a visible glitch during the first frame)
16479
0
    ImGuiContext& g = *ctx;
16480
0
    for (ImGuiWindow* window : g.Windows)
16481
0
    {
16482
0
        if (window->DockId == 0 || window->LastFrameActive < g.FrameCount - 1)
16483
0
            continue;
16484
0
        if (window->DockNode != NULL)
16485
0
            continue;
16486
16487
0
        ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
16488
0
        IM_ASSERT(node != NULL);   // This should have been called after DockContextBuildNodesFromSettings()
16489
0
        if (root_id == 0 || DockNodeGetRootNode(node)->ID == root_id)
16490
0
            DockNodeAddWindow(node, window, true);
16491
0
    }
16492
0
}
16493
16494
//-----------------------------------------------------------------------------
16495
// Docking: ImGuiDockContext Docking/Undocking functions
16496
//-----------------------------------------------------------------------------
16497
// - DockContextQueueDock()
16498
// - DockContextQueueUndockWindow()
16499
// - DockContextQueueUndockNode()
16500
// - DockContextQueueNotifyRemovedNode()
16501
// - DockContextProcessDock()
16502
// - DockContextProcessUndockWindow()
16503
// - DockContextProcessUndockNode()
16504
// - DockContextCalcDropPosForDocking()
16505
//-----------------------------------------------------------------------------
16506
16507
void ImGui::DockContextQueueDock(ImGuiContext* ctx, ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, float split_ratio, bool split_outer)
16508
0
{
16509
0
    IM_ASSERT(target != payload);
16510
0
    ImGuiDockRequest req;
16511
0
    req.Type = ImGuiDockRequestType_Dock;
16512
0
    req.DockTargetWindow = target;
16513
0
    req.DockTargetNode = target_node;
16514
0
    req.DockPayload = payload;
16515
0
    req.DockSplitDir = split_dir;
16516
0
    req.DockSplitRatio = split_ratio;
16517
0
    req.DockSplitOuter = split_outer;
16518
0
    ctx->DockContext.Requests.push_back(req);
16519
0
}
16520
16521
void ImGui::DockContextQueueUndockWindow(ImGuiContext* ctx, ImGuiWindow* window)
16522
0
{
16523
0
    ImGuiDockRequest req;
16524
0
    req.Type = ImGuiDockRequestType_Undock;
16525
0
    req.UndockTargetWindow = window;
16526
0
    ctx->DockContext.Requests.push_back(req);
16527
0
}
16528
16529
void ImGui::DockContextQueueUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
16530
0
{
16531
0
    ImGuiDockRequest req;
16532
0
    req.Type = ImGuiDockRequestType_Undock;
16533
0
    req.UndockTargetNode = node;
16534
0
    ctx->DockContext.Requests.push_back(req);
16535
0
}
16536
16537
void ImGui::DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node)
16538
0
{
16539
0
    ImGuiDockContext* dc = &ctx->DockContext;
16540
0
    for (ImGuiDockRequest& req : dc->Requests)
16541
0
        if (req.DockTargetNode == node)
16542
0
            req.Type = ImGuiDockRequestType_None;
16543
0
}
16544
16545
void ImGui::DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req)
16546
0
{
16547
0
    IM_ASSERT((req->Type == ImGuiDockRequestType_Dock && req->DockPayload != NULL) || (req->Type == ImGuiDockRequestType_Split && req->DockPayload == NULL));
16548
0
    IM_ASSERT(req->DockTargetWindow != NULL || req->DockTargetNode != NULL);
16549
16550
0
    ImGuiContext& g = *ctx;
16551
0
    IM_UNUSED(g);
16552
16553
0
    ImGuiWindow* payload_window = req->DockPayload;     // Optional
16554
0
    ImGuiWindow* target_window = req->DockTargetWindow;
16555
0
    ImGuiDockNode* node = req->DockTargetNode;
16556
0
    if (payload_window)
16557
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X target '%s' dock window '%s', split_dir %d\n", node ? node->ID : 0, target_window ? target_window->Name : "NULL", payload_window->Name, req->DockSplitDir);
16558
0
    else
16559
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X, split_dir %d\n", node ? node->ID : 0, req->DockSplitDir);
16560
16561
    // Decide which Tab will be selected at the end of the operation
16562
0
    ImGuiID next_selected_id = 0;
16563
0
    ImGuiDockNode* payload_node = NULL;
16564
0
    if (payload_window)
16565
0
    {
16566
0
        payload_node = payload_window->DockNodeAsHost;
16567
0
        payload_window->DockNodeAsHost = NULL; // Important to clear this as the node will have its life as a child which might be merged/deleted later.
16568
0
        if (payload_node && payload_node->IsLeafNode())
16569
0
            next_selected_id = payload_node->TabBar->NextSelectedTabId ? payload_node->TabBar->NextSelectedTabId : payload_node->TabBar->SelectedTabId;
16570
0
        if (payload_node == NULL)
16571
0
            next_selected_id = payload_window->TabId;
16572
0
    }
16573
16574
    // FIXME-DOCK: When we are trying to dock an existing single-window node into a loose window, transfer Node ID as well
16575
    // When processing an interactive split, usually LastFrameAlive will be < g.FrameCount. But DockBuilder operations can make it ==.
16576
0
    if (node)
16577
0
        IM_ASSERT(node->LastFrameAlive <= g.FrameCount);
16578
0
    if (node && target_window && node == target_window->DockNodeAsHost)
16579
0
        IM_ASSERT(node->Windows.Size > 0 || node->IsSplitNode() || node->IsCentralNode());
16580
16581
    // Create new node and add existing window to it
16582
0
    if (node == NULL)
16583
0
    {
16584
0
        node = DockContextAddNode(ctx, 0);
16585
0
        node->Pos = target_window->Pos;
16586
0
        node->Size = target_window->Size;
16587
0
        if (target_window->DockNodeAsHost == NULL)
16588
0
        {
16589
0
            DockNodeAddWindow(node, target_window, true);
16590
0
            node->TabBar->Tabs[0].Flags &= ~ImGuiTabItemFlags_Unsorted;
16591
0
            target_window->DockIsActive = true;
16592
0
        }
16593
0
    }
16594
16595
0
    ImGuiDir split_dir = req->DockSplitDir;
16596
0
    if (split_dir != ImGuiDir_None)
16597
0
    {
16598
        // Split into two, one side will be our payload node unless we are dropping a loose window
16599
0
        const ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
16600
0
        const int split_inheritor_child_idx = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0; // Current contents will be moved to the opposite side
16601
0
        const float split_ratio = req->DockSplitRatio;
16602
0
        DockNodeTreeSplit(ctx, node, split_axis, split_inheritor_child_idx, split_ratio, payload_node);  // payload_node may be NULL here!
16603
0
        ImGuiDockNode* new_node = node->ChildNodes[split_inheritor_child_idx ^ 1];
16604
0
        new_node->HostWindow = node->HostWindow;
16605
0
        node = new_node;
16606
0
    }
16607
0
    node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar);
16608
16609
0
    if (node != payload_node)
16610
0
    {
16611
        // Create tab bar before we call DockNodeMoveWindows (which would attempt to move the old tab-bar, which would lead us to payload tabs wrongly appearing before target tabs!)
16612
0
        if (node->Windows.Size > 0 && node->TabBar == NULL)
16613
0
        {
16614
0
            DockNodeAddTabBar(node);
16615
0
            for (int n = 0; n < node->Windows.Size; n++)
16616
0
                TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
16617
0
        }
16618
16619
0
        if (payload_node != NULL)
16620
0
        {
16621
            // Transfer full payload node (with 1+ child windows or child nodes)
16622
0
            if (payload_node->IsSplitNode())
16623
0
            {
16624
0
                if (node->Windows.Size > 0)
16625
0
                {
16626
                    // We can dock a split payload into a node that already has windows _only_ if our payload is a node tree with a single visible node.
16627
                    // In this situation, we move the windows of the target node into the currently visible node of the payload.
16628
                    // This allows us to preserve some of the underlying dock tree settings nicely.
16629
0
                    IM_ASSERT(payload_node->OnlyNodeWithWindows != NULL); // The docking should have been blocked by DockNodePreviewDockSetup() early on and never submitted.
16630
0
                    ImGuiDockNode* visible_node = payload_node->OnlyNodeWithWindows;
16631
0
                    if (visible_node->TabBar)
16632
0
                        IM_ASSERT(visible_node->TabBar->Tabs.Size > 0);
16633
0
                    DockNodeMoveWindows(node, visible_node);
16634
0
                    DockNodeMoveWindows(visible_node, node);
16635
0
                    DockSettingsRenameNodeReferences(node->ID, visible_node->ID);
16636
0
                }
16637
0
                if (node->IsCentralNode())
16638
0
                {
16639
                    // Central node property needs to be moved to a leaf node, pick the last focused one.
16640
                    // FIXME-DOCK: If we had to transfer other flags here, what would the policy be?
16641
0
                    ImGuiDockNode* last_focused_node = DockContextFindNodeByID(ctx, payload_node->LastFocusedNodeId);
16642
0
                    IM_ASSERT(last_focused_node != NULL);
16643
0
                    ImGuiDockNode* last_focused_root_node = DockNodeGetRootNode(last_focused_node);
16644
0
                    IM_ASSERT(last_focused_root_node == DockNodeGetRootNode(payload_node));
16645
0
                    last_focused_node->SetLocalFlags(last_focused_node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
16646
0
                    node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_CentralNode);
16647
0
                    last_focused_root_node->CentralNode = last_focused_node;
16648
0
                }
16649
16650
0
                IM_ASSERT(node->Windows.Size == 0);
16651
0
                DockNodeMoveChildNodes(node, payload_node);
16652
0
            }
16653
0
            else
16654
0
            {
16655
0
                const ImGuiID payload_dock_id = payload_node->ID;
16656
0
                DockNodeMoveWindows(node, payload_node);
16657
0
                DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
16658
0
            }
16659
0
            DockContextRemoveNode(ctx, payload_node, true);
16660
0
        }
16661
0
        else if (payload_window)
16662
0
        {
16663
            // Transfer single window
16664
0
            const ImGuiID payload_dock_id = payload_window->DockId;
16665
0
            node->VisibleWindow = payload_window;
16666
0
            DockNodeAddWindow(node, payload_window, true);
16667
0
            if (payload_dock_id != 0)
16668
0
                DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
16669
0
        }
16670
0
    }
16671
0
    else
16672
0
    {
16673
        // When docking a floating single window node we want to reevaluate auto-hiding of the tab bar
16674
0
        node->WantHiddenTabBarUpdate = true;
16675
0
    }
16676
16677
    // Update selection immediately
16678
0
    if (ImGuiTabBar* tab_bar = node->TabBar)
16679
0
        tab_bar->NextSelectedTabId = next_selected_id;
16680
0
    MarkIniSettingsDirty();
16681
0
}
16682
16683
// Problem:
16684
//   Undocking a large (~full screen) window would leave it so large that the bottom right sizing corner would more
16685
//   than likely be off the screen and the window would be hard to resize to fit on screen. This can be particularly problematic
16686
//   with 'ConfigWindowsMoveFromTitleBarOnly=true' and/or with 'ConfigWindowsResizeFromEdges=false' as well (the later can be
16687
//   due to missing ImGuiBackendFlags_HasMouseCursors backend flag).
16688
// Solution:
16689
//   When undocking a window we currently force its maximum size to 90% of the host viewport or monitor.
16690
// Reevaluate this when we implement preserving docked/undocked size ("docking_wip/undocked_size" branch).
16691
static ImVec2 FixLargeWindowsWhenUndocking(const ImVec2& size, ImGuiViewport* ref_viewport)
16692
0
{
16693
0
    if (ref_viewport == NULL)
16694
0
        return size;
16695
16696
0
    ImGuiContext& g = *GImGui;
16697
0
    ImVec2 max_size = ImTrunc(ref_viewport->WorkSize * 0.90f);
16698
0
    if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
16699
0
    {
16700
0
        const ImGuiPlatformMonitor* monitor = ImGui::GetViewportPlatformMonitor(ref_viewport);
16701
0
        max_size = ImTrunc(monitor->WorkSize * 0.90f);
16702
0
    }
16703
0
    return ImMin(size, max_size);
16704
0
}
16705
16706
void ImGui::DockContextProcessUndockWindow(ImGuiContext* ctx, ImGuiWindow* window, bool clear_persistent_docking_ref)
16707
0
{
16708
0
    ImGuiContext& g = *ctx;
16709
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockWindow window '%s', clear_persistent_docking_ref = %d\n", window->Name, clear_persistent_docking_ref);
16710
0
    if (window->DockNode)
16711
0
        DockNodeRemoveWindow(window->DockNode, window, clear_persistent_docking_ref ? 0 : window->DockId);
16712
0
    else
16713
0
        window->DockId = 0;
16714
0
    window->Collapsed = false;
16715
0
    window->DockIsActive = false;
16716
0
    window->DockNodeIsVisible = window->DockTabIsVisible = false;
16717
0
    window->Size = window->SizeFull = FixLargeWindowsWhenUndocking(window->SizeFull, window->Viewport);
16718
16719
0
    MarkIniSettingsDirty();
16720
0
}
16721
16722
void ImGui::DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
16723
0
{
16724
0
    ImGuiContext& g = *ctx;
16725
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockNode node %08X\n", node->ID);
16726
0
    IM_ASSERT(node->IsLeafNode());
16727
0
    IM_ASSERT(node->Windows.Size >= 1);
16728
16729
0
    if (node->IsRootNode() || node->IsCentralNode())
16730
0
    {
16731
        // In the case of a root node or central node, the node will have to stay in place. Create a new node to receive the payload.
16732
0
        ImGuiDockNode* new_node = DockContextAddNode(ctx, 0);
16733
0
        new_node->Pos = node->Pos;
16734
0
        new_node->Size = node->Size;
16735
0
        new_node->SizeRef = node->SizeRef;
16736
0
        DockNodeMoveWindows(new_node, node);
16737
0
        DockSettingsRenameNodeReferences(node->ID, new_node->ID);
16738
0
        node = new_node;
16739
0
    }
16740
0
    else
16741
0
    {
16742
        // Otherwise extract our node and merge our sibling back into the parent node.
16743
0
        IM_ASSERT(node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
16744
0
        int index_in_parent = (node->ParentNode->ChildNodes[0] == node) ? 0 : 1;
16745
0
        node->ParentNode->ChildNodes[index_in_parent] = NULL;
16746
0
        DockNodeTreeMerge(ctx, node->ParentNode, node->ParentNode->ChildNodes[index_in_parent ^ 1]);
16747
0
        node->ParentNode->AuthorityForViewport = ImGuiDataAuthority_Window; // The node that stays in place keeps the viewport, so our newly dragged out node will create a new viewport
16748
0
        node->ParentNode = NULL;
16749
0
    }
16750
0
    for (ImGuiWindow* window : node->Windows)
16751
0
    {
16752
0
        window->Flags &= ~ImGuiWindowFlags_ChildWindow;
16753
0
        if (window->ParentWindow)
16754
0
            window->ParentWindow->DC.ChildWindows.find_erase(window);
16755
0
        UpdateWindowParentAndRootLinks(window, window->Flags, NULL);
16756
0
    }
16757
0
    node->AuthorityForPos = node->AuthorityForSize = ImGuiDataAuthority_DockNode;
16758
0
    node->Size = FixLargeWindowsWhenUndocking(node->Size, node->Windows[0]->Viewport);
16759
0
    node->WantMouseMove = true;
16760
0
    MarkIniSettingsDirty();
16761
0
}
16762
16763
// This is mostly used for automation.
16764
bool ImGui::DockContextCalcDropPosForDocking(ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDir split_dir, bool split_outer, ImVec2* out_pos)
16765
0
{
16766
0
    if (target != NULL && target_node == NULL)
16767
0
        target_node = target->DockNode;
16768
16769
    // In DockNodePreviewDockSetup() for a root central node instead of showing both "inner" and "outer" drop rects
16770
    // (which would be functionally identical) we only show the outer one. Reflect this here.
16771
0
    if (target_node && target_node->ParentNode == NULL && target_node->IsCentralNode() && split_dir != ImGuiDir_None)
16772
0
        split_outer = true;
16773
0
    ImGuiDockPreviewData split_data;
16774
0
    DockNodePreviewDockSetup(target, target_node, payload_window, payload_node, &split_data, false, split_outer);
16775
0
    if (split_data.DropRectsDraw[split_dir+1].IsInverted())
16776
0
        return false;
16777
0
    *out_pos = split_data.DropRectsDraw[split_dir+1].GetCenter();
16778
0
    return true;
16779
0
}
16780
16781
//-----------------------------------------------------------------------------
16782
// Docking: ImGuiDockNode
16783
//-----------------------------------------------------------------------------
16784
// - DockNodeGetTabOrder()
16785
// - DockNodeAddWindow()
16786
// - DockNodeRemoveWindow()
16787
// - DockNodeMoveChildNodes()
16788
// - DockNodeMoveWindows()
16789
// - DockNodeApplyPosSizeToWindows()
16790
// - DockNodeHideHostWindow()
16791
// - ImGuiDockNodeFindInfoResults
16792
// - DockNodeFindInfo()
16793
// - DockNodeFindWindowByID()
16794
// - DockNodeUpdateFlagsAndCollapse()
16795
// - DockNodeUpdateHasCentralNodeFlag()
16796
// - DockNodeUpdateVisibleFlag()
16797
// - DockNodeStartMouseMovingWindow()
16798
// - DockNodeUpdate()
16799
// - DockNodeUpdateWindowMenu()
16800
// - DockNodeBeginAmendTabBar()
16801
// - DockNodeEndAmendTabBar()
16802
// - DockNodeUpdateTabBar()
16803
// - DockNodeAddTabBar()
16804
// - DockNodeRemoveTabBar()
16805
// - DockNodeIsDropAllowedOne()
16806
// - DockNodeIsDropAllowed()
16807
// - DockNodeCalcTabBarLayout()
16808
// - DockNodeCalcSplitRects()
16809
// - DockNodeCalcDropRectsAndTestMousePos()
16810
// - DockNodePreviewDockSetup()
16811
// - DockNodePreviewDockRender()
16812
//-----------------------------------------------------------------------------
16813
16814
ImGuiDockNode::ImGuiDockNode(ImGuiID id)
16815
0
{
16816
0
    ID = id;
16817
0
    SharedFlags = LocalFlags = LocalFlagsInWindows = MergedFlags = ImGuiDockNodeFlags_None;
16818
0
    ParentNode = ChildNodes[0] = ChildNodes[1] = NULL;
16819
0
    TabBar = NULL;
16820
0
    SplitAxis = ImGuiAxis_None;
16821
16822
0
    State = ImGuiDockNodeState_Unknown;
16823
0
    LastBgColor = IM_COL32_WHITE;
16824
0
    HostWindow = VisibleWindow = NULL;
16825
0
    CentralNode = OnlyNodeWithWindows = NULL;
16826
0
    CountNodeWithWindows = 0;
16827
0
    LastFrameAlive = LastFrameActive = LastFrameFocused = -1;
16828
0
    LastFocusedNodeId = 0;
16829
0
    SelectedTabId = 0;
16830
0
    WantCloseTabId = 0;
16831
0
    RefViewportId = 0;
16832
0
    AuthorityForPos = AuthorityForSize = ImGuiDataAuthority_DockNode;
16833
0
    AuthorityForViewport = ImGuiDataAuthority_Auto;
16834
0
    IsVisible = true;
16835
0
    IsFocused = HasCloseButton = HasWindowMenuButton = HasCentralNodeChild = false;
16836
0
    IsBgDrawnThisFrame = false;
16837
0
    WantCloseAll = WantLockSizeOnce = WantMouseMove = WantHiddenTabBarUpdate = WantHiddenTabBarToggle = false;
16838
0
}
16839
16840
ImGuiDockNode::~ImGuiDockNode()
16841
0
{
16842
0
    IM_DELETE(TabBar);
16843
0
    TabBar = NULL;
16844
0
    ChildNodes[0] = ChildNodes[1] = NULL;
16845
0
}
16846
16847
int ImGui::DockNodeGetTabOrder(ImGuiWindow* window)
16848
0
{
16849
0
    ImGuiTabBar* tab_bar = window->DockNode->TabBar;
16850
0
    if (tab_bar == NULL)
16851
0
        return -1;
16852
0
    ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, window->TabId);
16853
0
    return tab ? TabBarGetTabOrder(tab_bar, tab) : -1;
16854
0
}
16855
16856
static void DockNodeHideWindowDuringHostWindowCreation(ImGuiWindow* window)
16857
0
{
16858
0
    window->Hidden = true;
16859
0
    window->HiddenFramesCanSkipItems = window->Active ? 1 : 2;
16860
0
}
16861
16862
static void ImGui::DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar)
16863
0
{
16864
0
    ImGuiContext& g = *GImGui; (void)g;
16865
0
    if (window->DockNode)
16866
0
    {
16867
        // Can overwrite an existing window->DockNode (e.g. pointing to a disabled DockSpace node)
16868
0
        IM_ASSERT(window->DockNode->ID != node->ID);
16869
0
        DockNodeRemoveWindow(window->DockNode, window, 0);
16870
0
    }
16871
0
    IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL);
16872
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeAddWindow node 0x%08X window '%s'\n", node->ID, window->Name);
16873
16874
    // If more than 2 windows appeared on the same frame leading to the creation of a new hosting window,
16875
    // we'll hide windows until the host window is ready. Hide the 1st window after its been output (so it is not visible for one frame).
16876
    // We will call DockNodeHideWindowDuringHostWindowCreation() on ourselves in Begin()
16877
0
    if (node->HostWindow == NULL && node->Windows.Size == 1 && node->Windows[0]->WasActive == false)
16878
0
        DockNodeHideWindowDuringHostWindowCreation(node->Windows[0]);
16879
16880
0
    node->Windows.push_back(window);
16881
0
    node->WantHiddenTabBarUpdate = true;
16882
0
    window->DockNode = node;
16883
0
    window->DockId = node->ID;
16884
0
    window->DockIsActive = (node->Windows.Size > 1);
16885
0
    window->DockTabWantClose = false;
16886
16887
    // When reactivating a node with one or two loose window, the window pos/size/viewport are authoritative over the node storage.
16888
    // In particular it is important we init the viewport from the first window so we don't create two viewports and drop one.
16889
0
    if (node->HostWindow == NULL && node->IsFloatingNode())
16890
0
    {
16891
0
        if (node->AuthorityForPos == ImGuiDataAuthority_Auto)
16892
0
            node->AuthorityForPos = ImGuiDataAuthority_Window;
16893
0
        if (node->AuthorityForSize == ImGuiDataAuthority_Auto)
16894
0
            node->AuthorityForSize = ImGuiDataAuthority_Window;
16895
0
        if (node->AuthorityForViewport == ImGuiDataAuthority_Auto)
16896
0
            node->AuthorityForViewport = ImGuiDataAuthority_Window;
16897
0
    }
16898
16899
    // Add to tab bar if requested
16900
0
    if (add_to_tab_bar)
16901
0
    {
16902
0
        if (node->TabBar == NULL)
16903
0
        {
16904
0
            DockNodeAddTabBar(node);
16905
0
            node->TabBar->SelectedTabId = node->TabBar->NextSelectedTabId = node->SelectedTabId;
16906
16907
            // Add existing windows
16908
0
            for (int n = 0; n < node->Windows.Size - 1; n++)
16909
0
                TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
16910
0
        }
16911
0
        TabBarAddTab(node->TabBar, ImGuiTabItemFlags_Unsorted, window);
16912
0
    }
16913
16914
0
    DockNodeUpdateVisibleFlag(node);
16915
16916
    // Update this without waiting for the next time we Begin() in the window, so our host window will have the proper title bar color on its first frame.
16917
0
    if (node->HostWindow)
16918
0
        UpdateWindowParentAndRootLinks(window, window->Flags | ImGuiWindowFlags_ChildWindow, node->HostWindow);
16919
0
}
16920
16921
static void ImGui::DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id)
16922
0
{
16923
0
    ImGuiContext& g = *GImGui;
16924
0
    IM_ASSERT(window->DockNode == node);
16925
    //IM_ASSERT(window->RootWindowDockTree == node->HostWindow);
16926
    //IM_ASSERT(window->LastFrameActive < g.FrameCount);    // We may call this from Begin()
16927
0
    IM_ASSERT(save_dock_id == 0 || save_dock_id == node->ID);
16928
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeRemoveWindow node 0x%08X window '%s'\n", node->ID, window->Name);
16929
16930
0
    window->DockNode = NULL;
16931
0
    window->DockIsActive = window->DockTabWantClose = false;
16932
0
    window->DockId = save_dock_id;
16933
0
    window->Flags &= ~ImGuiWindowFlags_ChildWindow;
16934
0
    if (window->ParentWindow)
16935
0
        window->ParentWindow->DC.ChildWindows.find_erase(window);
16936
0
    UpdateWindowParentAndRootLinks(window, window->Flags, NULL); // Update immediately
16937
16938
0
    if (node->HostWindow && node->HostWindow->ViewportOwned)
16939
0
    {
16940
        // When undocking from a user interaction this will always run in NewFrame() and have not much effect.
16941
        // But mid-frame, if we clear viewport we need to mark window as hidden as well.
16942
0
        window->Viewport = NULL;
16943
0
        window->ViewportId = 0;
16944
0
        window->ViewportOwned = false;
16945
0
        window->Hidden = true;
16946
0
    }
16947
16948
    // Remove window
16949
0
    bool erased = false;
16950
0
    for (int n = 0; n < node->Windows.Size; n++)
16951
0
        if (node->Windows[n] == window)
16952
0
        {
16953
0
            node->Windows.erase(node->Windows.Data + n);
16954
0
            erased = true;
16955
0
            break;
16956
0
        }
16957
0
    if (!erased)
16958
0
        IM_ASSERT(erased);
16959
0
    if (node->VisibleWindow == window)
16960
0
        node->VisibleWindow = NULL;
16961
16962
    // Remove tab and possibly tab bar
16963
0
    node->WantHiddenTabBarUpdate = true;
16964
0
    if (node->TabBar)
16965
0
    {
16966
0
        TabBarRemoveTab(node->TabBar, window->TabId);
16967
0
        const int tab_count_threshold_for_tab_bar = node->IsCentralNode() ? 1 : 2;
16968
0
        if (node->Windows.Size < tab_count_threshold_for_tab_bar)
16969
0
            DockNodeRemoveTabBar(node);
16970
0
    }
16971
16972
0
    if (node->Windows.Size == 0 && !node->IsCentralNode() && !node->IsDockSpace() && window->DockId != node->ID)
16973
0
    {
16974
        // Automatic dock node delete themselves if they are not holding at least one tab
16975
0
        DockContextRemoveNode(&g, node, true);
16976
0
        return;
16977
0
    }
16978
16979
0
    if (node->Windows.Size == 1 && !node->IsCentralNode() && node->HostWindow)
16980
0
    {
16981
0
        ImGuiWindow* remaining_window = node->Windows[0];
16982
        // Note: we used to transport viewport ownership here.
16983
0
        remaining_window->Collapsed = node->HostWindow->Collapsed;
16984
0
    }
16985
16986
    // Update visibility immediately is required so the DockNodeUpdateRemoveInactiveChilds() processing can reflect changes up the tree
16987
0
    DockNodeUpdateVisibleFlag(node);
16988
0
}
16989
16990
static void ImGui::DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
16991
0
{
16992
0
    IM_ASSERT(dst_node->Windows.Size == 0);
16993
0
    dst_node->ChildNodes[0] = src_node->ChildNodes[0];
16994
0
    dst_node->ChildNodes[1] = src_node->ChildNodes[1];
16995
0
    if (dst_node->ChildNodes[0])
16996
0
        dst_node->ChildNodes[0]->ParentNode = dst_node;
16997
0
    if (dst_node->ChildNodes[1])
16998
0
        dst_node->ChildNodes[1]->ParentNode = dst_node;
16999
0
    dst_node->SplitAxis = src_node->SplitAxis;
17000
0
    dst_node->SizeRef = src_node->SizeRef;
17001
0
    src_node->ChildNodes[0] = src_node->ChildNodes[1] = NULL;
17002
0
}
17003
17004
static void ImGui::DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
17005
0
{
17006
    // Insert tabs in the same orders as currently ordered (node->Windows isn't ordered)
17007
0
    IM_ASSERT(src_node && dst_node && dst_node != src_node);
17008
0
    ImGuiTabBar* src_tab_bar = src_node->TabBar;
17009
0
    if (src_tab_bar != NULL)
17010
0
        IM_ASSERT(src_node->Windows.Size <= src_node->TabBar->Tabs.Size);
17011
17012
    // If the dst_node is empty we can just move the entire tab bar (to preserve selection, scrolling, etc.)
17013
0
    bool move_tab_bar = (src_tab_bar != NULL) && (dst_node->TabBar == NULL);
17014
0
    if (move_tab_bar)
17015
0
    {
17016
0
        dst_node->TabBar = src_node->TabBar;
17017
0
        src_node->TabBar = NULL;
17018
0
    }
17019
17020
    // Tab order is not important here, it is preserved by sorting in DockNodeUpdateTabBar().
17021
0
    for (ImGuiWindow* window : src_node->Windows)
17022
0
    {
17023
0
        window->DockNode = NULL;
17024
0
        window->DockIsActive = false;
17025
0
        DockNodeAddWindow(dst_node, window, !move_tab_bar);
17026
0
    }
17027
0
    src_node->Windows.clear();
17028
17029
0
    if (!move_tab_bar && src_node->TabBar)
17030
0
    {
17031
0
        if (dst_node->TabBar)
17032
0
            dst_node->TabBar->SelectedTabId = src_node->TabBar->SelectedTabId;
17033
0
        DockNodeRemoveTabBar(src_node);
17034
0
    }
17035
0
}
17036
17037
static void ImGui::DockNodeApplyPosSizeToWindows(ImGuiDockNode* node)
17038
0
{
17039
0
    for (ImGuiWindow* window : node->Windows)
17040
0
    {
17041
0
        SetWindowPos(window, node->Pos, ImGuiCond_Always); // We don't assign directly to Pos because it can break the calculation of SizeContents on next frame
17042
0
        SetWindowSize(window, node->Size, ImGuiCond_Always);
17043
0
    }
17044
0
}
17045
17046
static void ImGui::DockNodeHideHostWindow(ImGuiDockNode* node)
17047
0
{
17048
0
    if (node->HostWindow)
17049
0
    {
17050
0
        if (node->HostWindow->DockNodeAsHost == node)
17051
0
            node->HostWindow->DockNodeAsHost = NULL;
17052
0
        node->HostWindow = NULL;
17053
0
    }
17054
17055
0
    if (node->Windows.Size == 1)
17056
0
    {
17057
0
        node->VisibleWindow = node->Windows[0];
17058
0
        node->Windows[0]->DockIsActive = false;
17059
0
    }
17060
17061
0
    if (node->TabBar)
17062
0
        DockNodeRemoveTabBar(node);
17063
0
}
17064
17065
// Search function called once by root node in DockNodeUpdate()
17066
struct ImGuiDockNodeTreeInfo
17067
{
17068
    ImGuiDockNode*      CentralNode;
17069
    ImGuiDockNode*      FirstNodeWithWindows;
17070
    int                 CountNodesWithWindows;
17071
    //ImGuiWindowClass  WindowClassForMerges;
17072
17073
0
    ImGuiDockNodeTreeInfo() { memset(this, 0, sizeof(*this)); }
17074
};
17075
17076
static void DockNodeFindInfo(ImGuiDockNode* node, ImGuiDockNodeTreeInfo* info)
17077
0
{
17078
0
    if (node->Windows.Size > 0)
17079
0
    {
17080
0
        if (info->FirstNodeWithWindows == NULL)
17081
0
            info->FirstNodeWithWindows = node;
17082
0
        info->CountNodesWithWindows++;
17083
0
    }
17084
0
    if (node->IsCentralNode())
17085
0
    {
17086
0
        IM_ASSERT(info->CentralNode == NULL); // Should be only one
17087
0
        IM_ASSERT(node->IsLeafNode() && "If you get this assert: please submit .ini file + repro of actions leading to this.");
17088
0
        info->CentralNode = node;
17089
0
    }
17090
0
    if (info->CountNodesWithWindows > 1 && info->CentralNode != NULL)
17091
0
        return;
17092
0
    if (node->ChildNodes[0])
17093
0
        DockNodeFindInfo(node->ChildNodes[0], info);
17094
0
    if (node->ChildNodes[1])
17095
0
        DockNodeFindInfo(node->ChildNodes[1], info);
17096
0
}
17097
17098
static ImGuiWindow* ImGui::DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id)
17099
0
{
17100
0
    IM_ASSERT(id != 0);
17101
0
    for (ImGuiWindow* window : node->Windows)
17102
0
        if (window->ID == id)
17103
0
            return window;
17104
0
    return NULL;
17105
0
}
17106
17107
// - Remove inactive windows/nodes.
17108
// - Update visibility flag.
17109
static void ImGui::DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node)
17110
0
{
17111
0
    ImGuiContext& g = *GImGui;
17112
0
    IM_ASSERT(node->ParentNode == NULL || node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
17113
17114
    // Inherit most flags
17115
0
    if (node->ParentNode)
17116
0
        node->SharedFlags = node->ParentNode->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
17117
17118
    // Recurse into children
17119
    // There is the possibility that one of our child becoming empty will delete itself and moving its sibling contents into 'node'.
17120
    // If 'node->ChildNode[0]' delete itself, then 'node->ChildNode[1]->Windows' will be moved into 'node'
17121
    // If 'node->ChildNode[1]' delete itself, then 'node->ChildNode[0]->Windows' will be moved into 'node' and the "remove inactive windows" loop will have run twice on those windows (harmless)
17122
0
    node->HasCentralNodeChild = false;
17123
0
    if (node->ChildNodes[0])
17124
0
        DockNodeUpdateFlagsAndCollapse(node->ChildNodes[0]);
17125
0
    if (node->ChildNodes[1])
17126
0
        DockNodeUpdateFlagsAndCollapse(node->ChildNodes[1]);
17127
17128
    // Remove inactive windows, collapse nodes
17129
    // Merge node flags overrides stored in windows
17130
0
    node->LocalFlagsInWindows = ImGuiDockNodeFlags_None;
17131
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
17132
0
    {
17133
0
        ImGuiWindow* window = node->Windows[window_n];
17134
0
        IM_ASSERT(window->DockNode == node);
17135
17136
0
        bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
17137
0
        bool remove = false;
17138
0
        remove |= node_was_active && (window->LastFrameActive + 1 < g.FrameCount);
17139
0
        remove |= node_was_active && (node->WantCloseAll || node->WantCloseTabId == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument);  // Submit all _expected_ closure from last frame
17140
0
        remove |= (window->DockTabWantClose);
17141
0
        if (remove)
17142
0
        {
17143
0
            window->DockTabWantClose = false;
17144
0
            if (node->Windows.Size == 1 && !node->IsCentralNode())
17145
0
            {
17146
0
                DockNodeHideHostWindow(node);
17147
0
                node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
17148
0
                DockNodeRemoveWindow(node, window, node->ID); // Will delete the node so it'll be invalid on return
17149
0
                return;
17150
0
            }
17151
0
            DockNodeRemoveWindow(node, window, node->ID);
17152
0
            window_n--;
17153
0
            continue;
17154
0
        }
17155
17156
        // FIXME-DOCKING: Missing policies for conflict resolution, hence the "Experimental" tag on this.
17157
        //node->LocalFlagsInWindow &= ~window->WindowClass.DockNodeFlagsOverrideClear;
17158
0
        node->LocalFlagsInWindows |= window->WindowClass.DockNodeFlagsOverrideSet;
17159
0
    }
17160
0
    node->UpdateMergedFlags();
17161
17162
    // Auto-hide tab bar option
17163
0
    ImGuiDockNodeFlags node_flags = node->MergedFlags;
17164
0
    if (node->WantHiddenTabBarUpdate && node->Windows.Size == 1 && (node_flags & ImGuiDockNodeFlags_AutoHideTabBar) && !node->IsHiddenTabBar())
17165
0
        node->WantHiddenTabBarToggle = true;
17166
0
    node->WantHiddenTabBarUpdate = false;
17167
17168
    // Cancel toggling if we know our tab bar is enforced to be hidden at all times
17169
0
    if (node->WantHiddenTabBarToggle && node->VisibleWindow && (node->VisibleWindow->WindowClass.DockNodeFlagsOverrideSet & ImGuiDockNodeFlags_HiddenTabBar))
17170
0
        node->WantHiddenTabBarToggle = false;
17171
17172
    // Apply toggles at a single point of the frame (here!)
17173
0
    if (node->Windows.Size > 1)
17174
0
        node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar);
17175
0
    else if (node->WantHiddenTabBarToggle)
17176
0
        node->SetLocalFlags(node->LocalFlags ^ ImGuiDockNodeFlags_HiddenTabBar);
17177
0
    node->WantHiddenTabBarToggle = false;
17178
17179
0
    DockNodeUpdateVisibleFlag(node);
17180
0
}
17181
17182
// This is rarely called as DockNodeUpdateForRootNode() generally does it most frames.
17183
static void ImGui::DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node)
17184
0
{
17185
0
    node->HasCentralNodeChild = false;
17186
0
    if (node->ChildNodes[0])
17187
0
        DockNodeUpdateHasCentralNodeChild(node->ChildNodes[0]);
17188
0
    if (node->ChildNodes[1])
17189
0
        DockNodeUpdateHasCentralNodeChild(node->ChildNodes[1]);
17190
0
    if (node->IsRootNode())
17191
0
    {
17192
0
        ImGuiDockNode* mark_node = node->CentralNode;
17193
0
        while (mark_node)
17194
0
        {
17195
0
            mark_node->HasCentralNodeChild = true;
17196
0
            mark_node = mark_node->ParentNode;
17197
0
        }
17198
0
    }
17199
0
}
17200
17201
static void ImGui::DockNodeUpdateVisibleFlag(ImGuiDockNode* node)
17202
0
{
17203
    // Update visibility flag
17204
0
    bool is_visible = (node->ParentNode == NULL) ? node->IsDockSpace() : node->IsCentralNode();
17205
0
    is_visible |= (node->Windows.Size > 0);
17206
0
    is_visible |= (node->ChildNodes[0] && node->ChildNodes[0]->IsVisible);
17207
0
    is_visible |= (node->ChildNodes[1] && node->ChildNodes[1]->IsVisible);
17208
0
    node->IsVisible = is_visible;
17209
0
}
17210
17211
static void ImGui::DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window)
17212
0
{
17213
0
    ImGuiContext& g = *GImGui;
17214
0
    IM_ASSERT(node->WantMouseMove == true);
17215
0
    StartMouseMovingWindow(window);
17216
0
    g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - node->Pos;
17217
0
    g.MovingWindow = window; // If we are docked into a non moveable root window, StartMouseMovingWindow() won't set g.MovingWindow. Override that decision.
17218
0
    node->WantMouseMove = false;
17219
0
}
17220
17221
// Update CentralNode, OnlyNodeWithWindows, LastFocusedNodeID. Copy window class.
17222
static void ImGui::DockNodeUpdateForRootNode(ImGuiDockNode* node)
17223
0
{
17224
0
    DockNodeUpdateFlagsAndCollapse(node);
17225
17226
    // - Setup central node pointers
17227
    // - Find if there's only a single visible window in the hierarchy (in which case we need to display a regular title bar -> FIXME-DOCK: that last part is not done yet!)
17228
    // Cannot merge this with DockNodeUpdateFlagsAndCollapse() because FirstNodeWithWindows is found after window removal and child collapsing
17229
0
    ImGuiDockNodeTreeInfo info;
17230
0
    DockNodeFindInfo(node, &info);
17231
0
    node->CentralNode = info.CentralNode;
17232
0
    node->OnlyNodeWithWindows = (info.CountNodesWithWindows == 1) ? info.FirstNodeWithWindows : NULL;
17233
0
    node->CountNodeWithWindows = info.CountNodesWithWindows;
17234
0
    if (node->LastFocusedNodeId == 0 && info.FirstNodeWithWindows != NULL)
17235
0
        node->LastFocusedNodeId = info.FirstNodeWithWindows->ID;
17236
17237
    // Copy the window class from of our first window so it can be used for proper dock filtering.
17238
    // When node has mixed windows, prioritize the class with the most constraint (DockingAllowUnclassed = false) as the reference to copy.
17239
    // FIXME-DOCK: We don't recurse properly, this code could be reworked to work from DockNodeUpdateScanRec.
17240
0
    if (ImGuiDockNode* first_node_with_windows = info.FirstNodeWithWindows)
17241
0
    {
17242
0
        node->WindowClass = first_node_with_windows->Windows[0]->WindowClass;
17243
0
        for (int n = 1; n < first_node_with_windows->Windows.Size; n++)
17244
0
            if (first_node_with_windows->Windows[n]->WindowClass.DockingAllowUnclassed == false)
17245
0
            {
17246
0
                node->WindowClass = first_node_with_windows->Windows[n]->WindowClass;
17247
0
                break;
17248
0
            }
17249
0
    }
17250
17251
0
    ImGuiDockNode* mark_node = node->CentralNode;
17252
0
    while (mark_node)
17253
0
    {
17254
0
        mark_node->HasCentralNodeChild = true;
17255
0
        mark_node = mark_node->ParentNode;
17256
0
    }
17257
0
}
17258
17259
static void DockNodeSetupHostWindow(ImGuiDockNode* node, ImGuiWindow* host_window)
17260
0
{
17261
    // Remove ourselves from any previous different host window
17262
    // This can happen if a user mistakenly does (see #4295 for details):
17263
    //  - N+0: DockBuilderAddNode(id, 0)    // missing ImGuiDockNodeFlags_DockSpace
17264
    //  - N+1: NewFrame()                   // will create floating host window for that node
17265
    //  - N+1: DockSpace(id)                // requalify node as dockspace, moving host window
17266
0
    if (node->HostWindow && node->HostWindow != host_window && node->HostWindow->DockNodeAsHost == node)
17267
0
        node->HostWindow->DockNodeAsHost = NULL;
17268
17269
0
    host_window->DockNodeAsHost = node;
17270
0
    node->HostWindow = host_window;
17271
0
}
17272
17273
static void ImGui::DockNodeUpdate(ImGuiDockNode* node)
17274
0
{
17275
0
    ImGuiContext& g = *GImGui;
17276
0
    IM_ASSERT(node->LastFrameActive != g.FrameCount);
17277
0
    node->LastFrameAlive = g.FrameCount;
17278
0
    node->IsBgDrawnThisFrame = false;
17279
17280
0
    node->CentralNode = node->OnlyNodeWithWindows = NULL;
17281
0
    if (node->IsRootNode())
17282
0
        DockNodeUpdateForRootNode(node);
17283
17284
    // Remove tab bar if not needed
17285
0
    if (node->TabBar && node->IsNoTabBar())
17286
0
        DockNodeRemoveTabBar(node);
17287
17288
    // Early out for hidden root dock nodes (when all DockId references are in inactive windows, or there is only 1 floating window holding on the DockId)
17289
0
    bool want_to_hide_host_window = false;
17290
0
    if (node->IsFloatingNode())
17291
0
    {
17292
0
        if (node->Windows.Size <= 1 && node->IsLeafNode())
17293
0
            if (!g.IO.ConfigDockingAlwaysTabBar && (node->Windows.Size == 0 || !node->Windows[0]->WindowClass.DockingAlwaysTabBar))
17294
0
                want_to_hide_host_window = true;
17295
0
        if (node->CountNodeWithWindows == 0)
17296
0
            want_to_hide_host_window = true;
17297
0
    }
17298
0
    if (want_to_hide_host_window)
17299
0
    {
17300
0
        if (node->Windows.Size == 1)
17301
0
        {
17302
            // Floating window pos/size is authoritative
17303
0
            ImGuiWindow* single_window = node->Windows[0];
17304
0
            node->Pos = single_window->Pos;
17305
0
            node->Size = single_window->SizeFull;
17306
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
17307
17308
            // Transfer focus immediately so when we revert to a regular window it is immediately selected
17309
0
            if (node->HostWindow && g.NavWindow == node->HostWindow)
17310
0
                FocusWindow(single_window);
17311
0
            if (node->HostWindow)
17312
0
            {
17313
0
                IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Node %08X transfer Viewport %08X->%08X to Window '%s'\n", node->ID, node->HostWindow->Viewport->ID, single_window->ID, single_window->Name);
17314
0
                single_window->Viewport = node->HostWindow->Viewport;
17315
0
                single_window->ViewportId = node->HostWindow->ViewportId;
17316
0
                if (node->HostWindow->ViewportOwned)
17317
0
                {
17318
0
                    single_window->Viewport->ID = single_window->ID;
17319
0
                    single_window->Viewport->Window = single_window;
17320
0
                    single_window->ViewportOwned = true;
17321
0
                }
17322
0
            }
17323
0
            node->RefViewportId = single_window->ViewportId;
17324
0
        }
17325
17326
0
        DockNodeHideHostWindow(node);
17327
0
        node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
17328
0
        node->WantCloseAll = false;
17329
0
        node->WantCloseTabId = 0;
17330
0
        node->HasCloseButton = node->HasWindowMenuButton = false;
17331
0
        node->LastFrameActive = g.FrameCount;
17332
17333
0
        if (node->WantMouseMove && node->Windows.Size == 1)
17334
0
            DockNodeStartMouseMovingWindow(node, node->Windows[0]);
17335
0
        return;
17336
0
    }
17337
17338
    // In some circumstance we will defer creating the host window (so everything will be kept hidden),
17339
    // while the expected visible window is resizing itself.
17340
    // This is important for first-time (no ini settings restored) single window when io.ConfigDockingAlwaysTabBar is enabled,
17341
    // otherwise the node ends up using the minimum window size. Effectively those windows will take an extra frame to show up:
17342
    //   N+0: Begin(): window created (with no known size), node is created
17343
    //   N+1: DockNodeUpdate(): node skip creating host window / Begin(): window size applied, not visible
17344
    //   N+2: DockNodeUpdate(): node can create host window / Begin(): window becomes visible
17345
    // We could remove this frame if we could reliably calculate the expected window size during node update, before the Begin() code.
17346
    // It would require a generalization of CalcWindowExpectedSize(), probably extracting code away from Begin().
17347
    // In reality it isn't very important as user quickly ends up with size data in .ini file.
17348
0
    if (node->IsVisible && node->HostWindow == NULL && node->IsFloatingNode() && node->IsLeafNode())
17349
0
    {
17350
0
        IM_ASSERT(node->Windows.Size > 0);
17351
0
        ImGuiWindow* ref_window = NULL;
17352
0
        if (node->SelectedTabId != 0) // Note that we prune single-window-node settings on .ini loading, so this is generally 0 for them!
17353
0
            ref_window = DockNodeFindWindowByID(node, node->SelectedTabId);
17354
0
        if (ref_window == NULL)
17355
0
            ref_window = node->Windows[0];
17356
0
        if (ref_window->AutoFitFramesX > 0 || ref_window->AutoFitFramesY > 0)
17357
0
        {
17358
0
            node->State = ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing;
17359
0
            return;
17360
0
        }
17361
0
    }
17362
17363
0
    const ImGuiDockNodeFlags node_flags = node->MergedFlags;
17364
17365
    // Decide if the node will have a close button and a window menu button
17366
0
    node->HasWindowMenuButton = (node->Windows.Size > 0) && (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0;
17367
0
    node->HasCloseButton = false;
17368
0
    for (ImGuiWindow* window : node->Windows)
17369
0
    {
17370
        // FIXME-DOCK: Setting DockIsActive here means that for single active window in a leaf node, DockIsActive will be cleared until the next Begin() call.
17371
0
        node->HasCloseButton |= window->HasCloseButton;
17372
0
        window->DockIsActive = (node->Windows.Size > 1);
17373
0
    }
17374
0
    if (node_flags & ImGuiDockNodeFlags_NoCloseButton)
17375
0
        node->HasCloseButton = false;
17376
17377
    // Bind or create host window
17378
0
    ImGuiWindow* host_window = NULL;
17379
0
    bool beginned_into_host_window = false;
17380
0
    if (node->IsDockSpace())
17381
0
    {
17382
        // [Explicit root dockspace node]
17383
0
        IM_ASSERT(node->HostWindow);
17384
0
        host_window = node->HostWindow;
17385
0
    }
17386
0
    else
17387
0
    {
17388
        // [Automatic root or child nodes]
17389
0
        if (node->IsRootNode() && node->IsVisible)
17390
0
        {
17391
0
            ImGuiWindow* ref_window = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
17392
17393
            // Sync Pos
17394
0
            if (node->AuthorityForPos == ImGuiDataAuthority_Window && ref_window)
17395
0
                SetNextWindowPos(ref_window->Pos);
17396
0
            else if (node->AuthorityForPos == ImGuiDataAuthority_DockNode)
17397
0
                SetNextWindowPos(node->Pos);
17398
17399
            // Sync Size
17400
0
            if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
17401
0
                SetNextWindowSize(ref_window->SizeFull);
17402
0
            else if (node->AuthorityForSize == ImGuiDataAuthority_DockNode)
17403
0
                SetNextWindowSize(node->Size);
17404
17405
            // Sync Collapsed
17406
0
            if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
17407
0
                SetNextWindowCollapsed(ref_window->Collapsed);
17408
17409
            // Sync Viewport
17410
0
            if (node->AuthorityForViewport == ImGuiDataAuthority_Window && ref_window)
17411
0
                SetNextWindowViewport(ref_window->ViewportId);
17412
0
            else if (node->AuthorityForViewport == ImGuiDataAuthority_Window && node->RefViewportId != 0)
17413
0
                SetNextWindowViewport(node->RefViewportId);
17414
17415
0
            SetNextWindowClass(&node->WindowClass);
17416
17417
            // Begin into the host window
17418
0
            char window_label[20];
17419
0
            DockNodeGetHostWindowTitle(node, window_label, IM_ARRAYSIZE(window_label));
17420
0
            ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_DockNodeHost;
17421
0
            window_flags |= ImGuiWindowFlags_NoFocusOnAppearing;
17422
0
            window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoCollapse;
17423
0
            window_flags |= ImGuiWindowFlags_NoTitleBar;
17424
17425
0
            SetNextWindowBgAlpha(0.0f); // Don't set ImGuiWindowFlags_NoBackground because it disables borders
17426
0
            PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));
17427
0
            Begin(window_label, NULL, window_flags);
17428
0
            PopStyleVar();
17429
0
            beginned_into_host_window = true;
17430
17431
0
            host_window = g.CurrentWindow;
17432
0
            DockNodeSetupHostWindow(node, host_window);
17433
0
            host_window->DC.CursorPos = host_window->Pos;
17434
0
            node->Pos = host_window->Pos;
17435
0
            node->Size = host_window->Size;
17436
17437
            // We set ImGuiWindowFlags_NoFocusOnAppearing because we don't want the host window to take full focus (e.g. steal NavWindow)
17438
            // But we still it bring it to the front of display. There's no way to choose this precise behavior via window flags.
17439
            // One simple case to ponder if: window A has a toggle to create windows B/C/D. Dock B/C/D together, clear the toggle and enable it again.
17440
            // When reappearing B/C/D will request focus and be moved to the top of the display pile, but they are not linked to the dock host window
17441
            // during the frame they appear. The dock host window would keep its old display order, and the sorting in EndFrame would move B/C/D back
17442
            // after the dock host window, losing their top-most status.
17443
0
            if (node->HostWindow->Appearing)
17444
0
                BringWindowToDisplayFront(node->HostWindow);
17445
17446
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
17447
0
        }
17448
0
        else if (node->ParentNode)
17449
0
        {
17450
0
            node->HostWindow = host_window = node->ParentNode->HostWindow;
17451
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
17452
0
        }
17453
0
        if (node->WantMouseMove && node->HostWindow)
17454
0
            DockNodeStartMouseMovingWindow(node, node->HostWindow);
17455
0
    }
17456
0
    node->RefViewportId = 0; // Clear when we have a host window
17457
17458
    // Update focused node (the one whose title bar is highlight) within a node tree
17459
0
    if (node->IsSplitNode())
17460
0
        IM_ASSERT(node->TabBar == NULL);
17461
0
    if (node->IsRootNode())
17462
0
        if (ImGuiWindow* p_window = g.NavWindow ? g.NavWindow->RootWindow : NULL)
17463
0
            while (p_window != NULL && p_window->DockNode != NULL)
17464
0
            {
17465
0
                ImGuiDockNode* p_node = DockNodeGetRootNode(p_window->DockNode);
17466
0
                if (p_node == node)
17467
0
                {
17468
0
                    node->LastFocusedNodeId = p_window->DockNode->ID; // Note: not using root node ID!
17469
0
                    break;
17470
0
                }
17471
0
                p_window = p_node->HostWindow ? p_node->HostWindow->RootWindow : NULL;
17472
0
            }
17473
17474
    // Register a hit-test hole in the window unless we are currently dragging a window that is compatible with our dockspace
17475
0
    ImGuiDockNode* central_node = node->CentralNode;
17476
0
    const bool central_node_hole = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0 && central_node != NULL && central_node->IsEmpty();
17477
0
    bool central_node_hole_register_hit_test_hole = central_node_hole;
17478
0
    if (central_node_hole)
17479
0
        if (const ImGuiPayload* payload = ImGui::GetDragDropPayload())
17480
0
            if (payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && DockNodeIsDropAllowed(host_window, *(ImGuiWindow**)payload->Data))
17481
0
                central_node_hole_register_hit_test_hole = false;
17482
0
    if (central_node_hole_register_hit_test_hole)
17483
0
    {
17484
        // We add a little padding to match the "resize from edges" behavior and allow grabbing the splitter easily.
17485
        // (But we only add it if there's something else on the other side of the hole, otherwise for e.g. fullscreen
17486
        // covering passthru node we'd have a gap on the edge not covered by the hole)
17487
0
        IM_ASSERT(node->IsDockSpace()); // We cannot pass this flag without the DockSpace() api. Testing this because we also setup the hole in host_window->ParentNode
17488
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(central_node);
17489
0
        ImRect root_rect(root_node->Pos, root_node->Pos + root_node->Size);
17490
0
        ImRect hole_rect(central_node->Pos, central_node->Pos + central_node->Size);
17491
0
        if (hole_rect.Min.x > root_rect.Min.x) { hole_rect.Min.x += WINDOWS_HOVER_PADDING; }
17492
0
        if (hole_rect.Max.x < root_rect.Max.x) { hole_rect.Max.x -= WINDOWS_HOVER_PADDING; }
17493
0
        if (hole_rect.Min.y > root_rect.Min.y) { hole_rect.Min.y += WINDOWS_HOVER_PADDING; }
17494
0
        if (hole_rect.Max.y < root_rect.Max.y) { hole_rect.Max.y -= WINDOWS_HOVER_PADDING; }
17495
        //GetForegroundDrawList()->AddRect(hole_rect.Min, hole_rect.Max, IM_COL32(255, 0, 0, 255));
17496
0
        if (central_node_hole && !hole_rect.IsInverted())
17497
0
        {
17498
0
            SetWindowHitTestHole(host_window, hole_rect.Min, hole_rect.Max - hole_rect.Min);
17499
0
            if (host_window->ParentWindow)
17500
0
                SetWindowHitTestHole(host_window->ParentWindow, hole_rect.Min, hole_rect.Max - hole_rect.Min);
17501
0
        }
17502
0
    }
17503
17504
    // Update position/size, process and draw resizing splitters
17505
0
    if (node->IsRootNode() && host_window)
17506
0
    {
17507
0
        DockNodeTreeUpdatePosSize(node, host_window->Pos, host_window->Size);
17508
0
        PushStyleColor(ImGuiCol_Separator, g.Style.Colors[ImGuiCol_Border]);
17509
0
        PushStyleColor(ImGuiCol_SeparatorActive, g.Style.Colors[ImGuiCol_ResizeGripActive]);
17510
0
        PushStyleColor(ImGuiCol_SeparatorHovered, g.Style.Colors[ImGuiCol_ResizeGripHovered]);
17511
0
        DockNodeTreeUpdateSplitter(node);
17512
0
        PopStyleColor(3);
17513
0
    }
17514
17515
    // Draw empty node background (currently can only be the Central Node)
17516
0
    if (host_window && node->IsEmpty() && node->IsVisible)
17517
0
    {
17518
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
17519
0
        node->LastBgColor = (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) ? 0 : GetColorU32(ImGuiCol_DockingEmptyBg);
17520
0
        if (node->LastBgColor != 0)
17521
0
            host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, node->LastBgColor);
17522
0
        node->IsBgDrawnThisFrame = true;
17523
0
    }
17524
17525
    // Draw whole dockspace background if ImGuiDockNodeFlags_PassthruCentralNode if set.
17526
    // We need to draw a background at the root level if requested by ImGuiDockNodeFlags_PassthruCentralNode, but we will only know the correct pos/size
17527
    // _after_ processing the resizing splitters. So we are using the DrawList channel splitting facility to submit drawing primitives out of order!
17528
0
    const bool render_dockspace_bg = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0;
17529
0
    if (render_dockspace_bg && node->IsVisible)
17530
0
    {
17531
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
17532
0
        if (central_node_hole)
17533
0
            RenderRectFilledWithHole(host_window->DrawList, node->Rect(), central_node->Rect(), GetColorU32(ImGuiCol_WindowBg), 0.0f);
17534
0
        else
17535
0
            host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, GetColorU32(ImGuiCol_WindowBg), 0.0f);
17536
0
    }
17537
17538
    // Draw and populate Tab Bar
17539
0
    if (host_window)
17540
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
17541
0
    if (host_window && node->Windows.Size > 0)
17542
0
    {
17543
0
        DockNodeUpdateTabBar(node, host_window);
17544
0
    }
17545
0
    else
17546
0
    {
17547
0
        node->WantCloseAll = false;
17548
0
        node->WantCloseTabId = 0;
17549
0
        node->IsFocused = false;
17550
0
    }
17551
0
    if (node->TabBar && node->TabBar->SelectedTabId)
17552
0
        node->SelectedTabId = node->TabBar->SelectedTabId;
17553
0
    else if (node->Windows.Size > 0)
17554
0
        node->SelectedTabId = node->Windows[0]->TabId;
17555
17556
    // Draw payload drop target
17557
0
    if (host_window && node->IsVisible)
17558
0
        if (node->IsRootNode() && (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != host_window))
17559
0
            BeginDockableDragDropTarget(host_window);
17560
17561
    // We update this after DockNodeUpdateTabBar()
17562
0
    node->LastFrameActive = g.FrameCount;
17563
17564
    // Recurse into children
17565
    // FIXME-DOCK FIXME-OPT: Should not need to recurse into children
17566
0
    if (host_window)
17567
0
    {
17568
0
        if (node->ChildNodes[0])
17569
0
            DockNodeUpdate(node->ChildNodes[0]);
17570
0
        if (node->ChildNodes[1])
17571
0
            DockNodeUpdate(node->ChildNodes[1]);
17572
17573
        // Render outer borders last (after the tab bar)
17574
0
        if (node->IsRootNode())
17575
0
            RenderWindowOuterBorders(host_window);
17576
0
    }
17577
17578
    // End host window
17579
0
    if (beginned_into_host_window) //-V1020
17580
0
        End();
17581
0
}
17582
17583
// Compare TabItem nodes given the last known DockOrder (will persist in .ini file as hint), used to sort tabs when multiple tabs are added on the same frame.
17584
static int IMGUI_CDECL TabItemComparerByDockOrder(const void* lhs, const void* rhs)
17585
0
{
17586
0
    ImGuiWindow* a = ((const ImGuiTabItem*)lhs)->Window;
17587
0
    ImGuiWindow* b = ((const ImGuiTabItem*)rhs)->Window;
17588
0
    if (int d = ((a->DockOrder == -1) ? INT_MAX : a->DockOrder) - ((b->DockOrder == -1) ? INT_MAX : b->DockOrder))
17589
0
        return d;
17590
0
    return (a->BeginOrderWithinContext - b->BeginOrderWithinContext);
17591
0
}
17592
17593
// Default handler for g.DockNodeWindowMenuHandler(): display the list of windows for a given dock-node.
17594
// This is exceptionally stored in a function pointer to also user applications to tweak this menu (undocumented)
17595
// Custom overrides may want to decorate, group, sort entries.
17596
// Please note those are internal structures: if you copy this expect occasional breakage.
17597
// (if you don't need to modify the "Tabs.Size == 1" behavior/path it is recommend you call this function in your handler)
17598
void ImGui::DockNodeWindowMenuHandler_Default(ImGuiContext* ctx, ImGuiDockNode* node, ImGuiTabBar* tab_bar)
17599
0
{
17600
0
    IM_UNUSED(ctx);
17601
0
    if (tab_bar->Tabs.Size == 1)
17602
0
    {
17603
        // "Hide tab bar" option. Being one of our rare user-facing string we pull it from a table.
17604
0
        if (MenuItem(LocalizeGetMsg(ImGuiLocKey_DockingHideTabBar), NULL, node->IsHiddenTabBar()))
17605
0
            node->WantHiddenTabBarToggle = true;
17606
0
    }
17607
0
    else
17608
0
    {
17609
        // Display a selectable list of windows in this docking node
17610
0
        for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
17611
0
        {
17612
0
            ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
17613
0
            if (tab->Flags & ImGuiTabItemFlags_Button)
17614
0
                continue;
17615
0
            if (Selectable(TabBarGetTabName(tab_bar, tab), tab->ID == tab_bar->SelectedTabId))
17616
0
                TabBarQueueFocus(tab_bar, tab);
17617
0
            SameLine();
17618
0
            Text("   ");
17619
0
        }
17620
0
    }
17621
0
}
17622
17623
static void ImGui::DockNodeWindowMenuUpdate(ImGuiDockNode* node, ImGuiTabBar* tab_bar)
17624
0
{
17625
    // Try to position the menu so it is more likely to stays within the same viewport
17626
0
    ImGuiContext& g = *GImGui;
17627
0
    if (g.Style.WindowMenuButtonPosition == ImGuiDir_Left)
17628
0
        SetNextWindowPos(ImVec2(node->Pos.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(0.0f, 0.0f));
17629
0
    else
17630
0
        SetNextWindowPos(ImVec2(node->Pos.x + node->Size.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(1.0f, 0.0f));
17631
0
    if (BeginPopup("#WindowMenu"))
17632
0
    {
17633
0
        node->IsFocused = true;
17634
0
        g.DockNodeWindowMenuHandler(&g, node, tab_bar);
17635
0
        EndPopup();
17636
0
    }
17637
0
}
17638
17639
// User helper to append/amend into a dock node tab bar. Most commonly used to add e.g. a "+" button.
17640
bool ImGui::DockNodeBeginAmendTabBar(ImGuiDockNode* node)
17641
0
{
17642
0
    if (node->TabBar == NULL || node->HostWindow == NULL)
17643
0
        return false;
17644
0
    if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
17645
0
        return false;
17646
0
    if (node->TabBar->ID == 0)
17647
0
        return false;
17648
0
    Begin(node->HostWindow->Name);
17649
0
    PushOverrideID(node->ID);
17650
0
    bool ret = BeginTabBarEx(node->TabBar, node->TabBar->BarRect, node->TabBar->Flags);
17651
0
    IM_UNUSED(ret);
17652
0
    IM_ASSERT(ret);
17653
0
    return true;
17654
0
}
17655
17656
void ImGui::DockNodeEndAmendTabBar()
17657
0
{
17658
0
    EndTabBar();
17659
0
    PopID();
17660
0
    End();
17661
0
}
17662
17663
static bool IsDockNodeTitleBarHighlighted(ImGuiDockNode* node, ImGuiDockNode* root_node)
17664
0
{
17665
    // CTRL+Tab highlight (only highlighting leaf node, not whole hierarchy)
17666
0
    ImGuiContext& g = *GImGui;
17667
0
    if (g.NavWindowingTarget)
17668
0
        return (g.NavWindowingTarget->DockNode == node);
17669
17670
    // FIXME-DOCKING: May want alternative to treat central node void differently? e.g. if (g.NavWindow == host_window)
17671
0
    if (g.NavWindow && root_node->LastFocusedNodeId == node->ID)
17672
0
    {
17673
        // FIXME: This could all be backed in RootWindowForTitleBarHighlight? Probably need to reorganize for both dock nodes + other RootWindowForTitleBarHighlight users (not-node)
17674
0
        ImGuiWindow* parent_window = g.NavWindow->RootWindow;
17675
0
        while (parent_window->Flags & ImGuiWindowFlags_ChildMenu)
17676
0
            parent_window = parent_window->ParentWindow->RootWindow;
17677
0
        ImGuiDockNode* start_parent_node = parent_window->DockNodeAsHost ? parent_window->DockNodeAsHost : parent_window->DockNode;
17678
0
        for (ImGuiDockNode* parent_node = start_parent_node; parent_node != NULL; parent_node = parent_node->HostWindow ? parent_node->HostWindow->RootWindow->DockNode : NULL)
17679
0
            if ((parent_node = ImGui::DockNodeGetRootNode(parent_node)) == root_node)
17680
0
                return true;
17681
0
    }
17682
0
    return false;
17683
0
}
17684
17685
// Submit the tab bar corresponding to a dock node and various housekeeping details.
17686
static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window)
17687
0
{
17688
0
    ImGuiContext& g = *GImGui;
17689
0
    ImGuiStyle& style = g.Style;
17690
17691
0
    const bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
17692
0
    const bool closed_all = node->WantCloseAll && node_was_active;
17693
0
    const ImGuiID closed_one = node->WantCloseTabId && node_was_active;
17694
0
    node->WantCloseAll = false;
17695
0
    node->WantCloseTabId = 0;
17696
17697
    // Decide if we should use a focused title bar color
17698
0
    bool is_focused = false;
17699
0
    ImGuiDockNode* root_node = DockNodeGetRootNode(node);
17700
0
    if (IsDockNodeTitleBarHighlighted(node, root_node))
17701
0
        is_focused = true;
17702
17703
    // Hidden tab bar will show a triangle on the upper-left (in Begin)
17704
0
    if (node->IsHiddenTabBar() || node->IsNoTabBar())
17705
0
    {
17706
0
        node->VisibleWindow = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
17707
0
        node->IsFocused = is_focused;
17708
0
        if (is_focused)
17709
0
            node->LastFrameFocused = g.FrameCount;
17710
0
        if (node->VisibleWindow)
17711
0
        {
17712
            // Notify root of visible window (used to display title in OS task bar)
17713
0
            if (is_focused || root_node->VisibleWindow == NULL)
17714
0
                root_node->VisibleWindow = node->VisibleWindow;
17715
0
            if (node->TabBar)
17716
0
                node->TabBar->VisibleTabId = node->VisibleWindow->TabId;
17717
0
        }
17718
0
        return;
17719
0
    }
17720
17721
    // Move ourselves to the Menu layer (so we can be accessed by tapping Alt) + undo SkipItems flag in order to draw over the title bar even if the window is collapsed
17722
0
    bool backup_skip_item = host_window->SkipItems;
17723
0
    if (!node->IsDockSpace())
17724
0
    {
17725
0
        host_window->SkipItems = false;
17726
0
        host_window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
17727
0
    }
17728
17729
    // Use PushOverrideID() instead of PushID() to use the node id _without_ the host window ID.
17730
    // This is to facilitate computing those ID from the outside, and will affect more or less only the ID of the collapse button, popup and tabs,
17731
    // as docked windows themselves will override the stack with their own root ID.
17732
0
    PushOverrideID(node->ID);
17733
0
    ImGuiTabBar* tab_bar = node->TabBar;
17734
0
    bool tab_bar_is_recreated = (tab_bar == NULL); // Tab bar are automatically destroyed when a node gets hidden
17735
0
    if (tab_bar == NULL)
17736
0
    {
17737
0
        DockNodeAddTabBar(node);
17738
0
        tab_bar = node->TabBar;
17739
0
    }
17740
17741
0
    ImGuiID focus_tab_id = 0;
17742
0
    node->IsFocused = is_focused;
17743
17744
0
    const ImGuiDockNodeFlags node_flags = node->MergedFlags;
17745
0
    const bool has_window_menu_button = (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0 && (style.WindowMenuButtonPosition != ImGuiDir_None);
17746
17747
    // In a dock node, the Collapse Button turns into the Window Menu button.
17748
    // FIXME-DOCK FIXME-OPT: Could we recycle popups id across multiple dock nodes?
17749
0
    if (has_window_menu_button && IsPopupOpen("#WindowMenu"))
17750
0
    {
17751
0
        ImGuiID next_selected_tab_id = tab_bar->NextSelectedTabId;
17752
0
        DockNodeWindowMenuUpdate(node, tab_bar);
17753
0
        if (tab_bar->NextSelectedTabId != 0 && tab_bar->NextSelectedTabId != next_selected_tab_id)
17754
0
            focus_tab_id = tab_bar->NextSelectedTabId;
17755
0
        is_focused |= node->IsFocused;
17756
0
    }
17757
17758
    // Layout
17759
0
    ImRect title_bar_rect, tab_bar_rect;
17760
0
    ImVec2 window_menu_button_pos;
17761
0
    ImVec2 close_button_pos;
17762
0
    DockNodeCalcTabBarLayout(node, &title_bar_rect, &tab_bar_rect, &window_menu_button_pos, &close_button_pos);
17763
17764
    // Submit new tabs, they will be added as Unsorted and sorted below based on relative DockOrder value.
17765
0
    const int tabs_count_old = tab_bar->Tabs.Size;
17766
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
17767
0
    {
17768
0
        ImGuiWindow* window = node->Windows[window_n];
17769
0
        if (TabBarFindTabByID(tab_bar, window->TabId) == NULL)
17770
0
            TabBarAddTab(tab_bar, ImGuiTabItemFlags_Unsorted, window);
17771
0
    }
17772
17773
    // Title bar
17774
0
    if (is_focused)
17775
0
        node->LastFrameFocused = g.FrameCount;
17776
0
    ImU32 title_bar_col = GetColorU32(host_window->Collapsed ? ImGuiCol_TitleBgCollapsed : is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
17777
0
    ImDrawFlags rounding_flags = CalcRoundingFlagsForRectInRect(title_bar_rect, host_window->Rect(), g.Style.DockingSeparatorSize);
17778
0
    host_window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, host_window->WindowRounding, rounding_flags);
17779
17780
    // Docking/Collapse button
17781
0
    if (has_window_menu_button)
17782
0
    {
17783
0
        if (CollapseButton(host_window->GetID("#COLLAPSE"), window_menu_button_pos, node)) // == DockNodeGetWindowMenuButtonId(node)
17784
0
            OpenPopup("#WindowMenu");
17785
0
        if (IsItemActive())
17786
0
            focus_tab_id = tab_bar->SelectedTabId;
17787
0
        if (IsItemHovered(ImGuiHoveredFlags_ForTooltip | ImGuiHoveredFlags_DelayNormal) && g.HoveredIdTimer > 0.5f)
17788
0
            SetTooltip("%s", LocalizeGetMsg(ImGuiLocKey_DockingDragToUndockOrMoveNode));
17789
0
    }
17790
17791
    // If multiple tabs are appearing on the same frame, sort them based on their persistent DockOrder value
17792
0
    int tabs_unsorted_start = tab_bar->Tabs.Size;
17793
0
    for (int tab_n = tab_bar->Tabs.Size - 1; tab_n >= 0 && (tab_bar->Tabs[tab_n].Flags & ImGuiTabItemFlags_Unsorted); tab_n--)
17794
0
    {
17795
        // FIXME-DOCK: Consider only clearing the flag after the tab has been alive for a few consecutive frames, allowing late comers to not break sorting?
17796
0
        tab_bar->Tabs[tab_n].Flags &= ~ImGuiTabItemFlags_Unsorted;
17797
0
        tabs_unsorted_start = tab_n;
17798
0
    }
17799
0
    if (tab_bar->Tabs.Size > tabs_unsorted_start)
17800
0
    {
17801
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] In node 0x%08X: %d new appearing tabs:%s\n", node->ID, tab_bar->Tabs.Size - tabs_unsorted_start, (tab_bar->Tabs.Size > tabs_unsorted_start + 1) ? " (will sort)" : "");
17802
0
        for (int tab_n = tabs_unsorted_start; tab_n < tab_bar->Tabs.Size; tab_n++)
17803
0
        {
17804
0
            ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
17805
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] - Tab 0x%08X '%s' Order %d\n", tab->ID, TabBarGetTabName(tab_bar, tab), tab->Window ? tab->Window->DockOrder : -1);
17806
0
        }
17807
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] SelectedTabId = 0x%08X, NavWindow->TabId = 0x%08X\n", node->SelectedTabId, g.NavWindow ? g.NavWindow->TabId : -1);
17808
0
        if (tab_bar->Tabs.Size > tabs_unsorted_start + 1)
17809
0
            ImQsort(tab_bar->Tabs.Data + tabs_unsorted_start, tab_bar->Tabs.Size - tabs_unsorted_start, sizeof(ImGuiTabItem), TabItemComparerByDockOrder);
17810
0
    }
17811
17812
    // Apply NavWindow focus back to the tab bar
17813
0
    if (g.NavWindow && g.NavWindow->RootWindow->DockNode == node)
17814
0
        tab_bar->SelectedTabId = g.NavWindow->RootWindow->TabId;
17815
17816
    // Selected newly added tabs, or persistent tab ID if the tab bar was just recreated
17817
0
    if (tab_bar_is_recreated && TabBarFindTabByID(tab_bar, node->SelectedTabId) != NULL)
17818
0
        tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = node->SelectedTabId;
17819
0
    else if (tab_bar->Tabs.Size > tabs_count_old)
17820
0
        tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = tab_bar->Tabs.back().Window->TabId;
17821
17822
    // Begin tab bar
17823
0
    ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_AutoSelectNewTabs; // | ImGuiTabBarFlags_NoTabListScrollingButtons);
17824
0
    tab_bar_flags |= ImGuiTabBarFlags_SaveSettings | ImGuiTabBarFlags_DockNode;// | ImGuiTabBarFlags_FittingPolicyScroll;
17825
0
    tab_bar_flags |= ImGuiTabBarFlags_DrawSelectedOverline;
17826
0
    if (!host_window->Collapsed && is_focused)
17827
0
        tab_bar_flags |= ImGuiTabBarFlags_IsFocused;
17828
0
    tab_bar->ID = GetID("#TabBar");
17829
0
    tab_bar->SeparatorMinX = node->Pos.x + host_window->WindowBorderSize; // Separator cover the whole node width
17830
0
    tab_bar->SeparatorMaxX = node->Pos.x + node->Size.x - host_window->WindowBorderSize;
17831
0
    BeginTabBarEx(tab_bar, tab_bar_rect, tab_bar_flags);
17832
    //host_window->DrawList->AddRect(tab_bar_rect.Min, tab_bar_rect.Max, IM_COL32(255,0,255,255));
17833
17834
    // Backup style colors
17835
0
    ImVec4 backup_style_cols[ImGuiWindowDockStyleCol_COUNT];
17836
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
17837
0
        backup_style_cols[color_n] = g.Style.Colors[GWindowDockStyleColors[color_n]];
17838
17839
    // Submit actual tabs
17840
0
    node->VisibleWindow = NULL;
17841
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
17842
0
    {
17843
0
        ImGuiWindow* window = node->Windows[window_n];
17844
0
        if ((closed_all || closed_one == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument))
17845
0
            continue;
17846
0
        if (window->LastFrameActive + 1 >= g.FrameCount || !node_was_active)
17847
0
        {
17848
0
            ImGuiTabItemFlags tab_item_flags = 0;
17849
0
            tab_item_flags |= window->WindowClass.TabItemFlagsOverrideSet;
17850
0
            if (window->Flags & ImGuiWindowFlags_UnsavedDocument)
17851
0
                tab_item_flags |= ImGuiTabItemFlags_UnsavedDocument;
17852
0
            if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton)
17853
0
                tab_item_flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton;
17854
17855
            // Apply stored style overrides for the window
17856
0
            for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
17857
0
                g.Style.Colors[GWindowDockStyleColors[color_n]] = ColorConvertU32ToFloat4(window->DockStyle.Colors[color_n]);
17858
17859
            // Note that TabItemEx() calls TabBarCalcTabID() so our tab item ID will ignore the current ID stack (rightly so)
17860
0
            bool tab_open = true;
17861
0
            TabItemEx(tab_bar, window->Name, window->HasCloseButton ? &tab_open : NULL, tab_item_flags, window);
17862
0
            if (!tab_open)
17863
0
                node->WantCloseTabId = window->TabId;
17864
0
            if (tab_bar->VisibleTabId == window->TabId)
17865
0
                node->VisibleWindow = window;
17866
17867
            // Store last item data so it can be queried with IsItemXXX functions after the user Begin() call
17868
0
            window->DockTabItemStatusFlags = g.LastItemData.StatusFlags;
17869
0
            window->DockTabItemRect = g.LastItemData.Rect;
17870
17871
            // Update navigation ID on menu layer
17872
0
            if (g.NavWindow && g.NavWindow->RootWindow == window && (window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0)
17873
0
                host_window->NavLastIds[1] = window->TabId;
17874
0
        }
17875
0
    }
17876
17877
    // Restore style colors
17878
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
17879
0
        g.Style.Colors[GWindowDockStyleColors[color_n]] = backup_style_cols[color_n];
17880
17881
    // Notify root of visible window (used to display title in OS task bar)
17882
0
    if (node->VisibleWindow)
17883
0
        if (is_focused || root_node->VisibleWindow == NULL)
17884
0
            root_node->VisibleWindow = node->VisibleWindow;
17885
17886
    // Close button (after VisibleWindow was updated)
17887
    // Note that VisibleWindow may have been overrided by CTRL+Tabbing, so VisibleWindow->TabId may be != from tab_bar->SelectedTabId
17888
0
    const bool close_button_is_enabled = node->HasCloseButton && node->VisibleWindow && node->VisibleWindow->HasCloseButton;
17889
0
    const bool close_button_is_visible = node->HasCloseButton;
17890
    //const bool close_button_is_visible = close_button_is_enabled; // Most people would expect this behavior of not even showing the button (leaving a hole since we can't claim that space as other windows in the tba bar have one)
17891
0
    if (close_button_is_visible)
17892
0
    {
17893
0
        if (!close_button_is_enabled)
17894
0
        {
17895
0
            PushItemFlag(ImGuiItemFlags_Disabled, true);
17896
0
            PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_Text] * ImVec4(1.0f,1.0f,1.0f,0.4f));
17897
0
        }
17898
0
        if (CloseButton(host_window->GetID("#CLOSE"), close_button_pos))
17899
0
        {
17900
0
            node->WantCloseAll = true;
17901
0
            for (int n = 0; n < tab_bar->Tabs.Size; n++)
17902
0
                TabBarCloseTab(tab_bar, &tab_bar->Tabs[n]);
17903
0
        }
17904
        //if (IsItemActive())
17905
        //    focus_tab_id = tab_bar->SelectedTabId;
17906
0
        if (!close_button_is_enabled)
17907
0
        {
17908
0
            PopStyleColor();
17909
0
            PopItemFlag();
17910
0
        }
17911
0
    }
17912
17913
    // When clicking on the title bar outside of tabs, we still focus the selected tab for that node
17914
    // FIXME: TabItems submitted earlier use AllowItemOverlap so we manually perform a more specific test for now (hovered || held) in order to not cover them.
17915
0
    ImGuiID title_bar_id = host_window->GetID("#TITLEBAR");
17916
0
    if (g.HoveredId == 0 || g.HoveredId == title_bar_id || g.ActiveId == title_bar_id)
17917
0
    {
17918
        // AllowOverlap mode required for appending into dock node tab bar,
17919
        // otherwise dragging window will steal HoveredId and amended tabs cannot get them.
17920
0
        bool held;
17921
0
        KeepAliveID(title_bar_id);
17922
0
        ButtonBehavior(title_bar_rect, title_bar_id, NULL, &held, ImGuiButtonFlags_AllowOverlap);
17923
0
        if (g.HoveredId == title_bar_id)
17924
0
        {
17925
0
            g.LastItemData.ID = title_bar_id;
17926
0
        }
17927
0
        if (held)
17928
0
        {
17929
0
            if (IsMouseClicked(0))
17930
0
                focus_tab_id = tab_bar->SelectedTabId;
17931
17932
            // Forward moving request to selected window
17933
0
            if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_bar->SelectedTabId))
17934
0
                StartMouseMovingWindowOrNode(tab->Window ? tab->Window : node->HostWindow, node, false); // Undock from tab bar empty space
17935
0
        }
17936
0
    }
17937
17938
    // Forward focus from host node to selected window
17939
    //if (is_focused && g.NavWindow == host_window && !g.NavWindowingTarget)
17940
    //    focus_tab_id = tab_bar->SelectedTabId;
17941
17942
    // When clicked on a tab we requested focus to the docked child
17943
    // This overrides the value set by "forward focus from host node to selected window".
17944
0
    if (tab_bar->NextSelectedTabId)
17945
0
        focus_tab_id = tab_bar->NextSelectedTabId;
17946
17947
    // Apply navigation focus
17948
0
    if (focus_tab_id != 0)
17949
0
        if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, focus_tab_id))
17950
0
            if (tab->Window)
17951
0
            {
17952
0
                FocusWindow(tab->Window);
17953
0
                NavInitWindow(tab->Window, false);
17954
0
            }
17955
17956
0
    EndTabBar();
17957
0
    PopID();
17958
17959
    // Restore SkipItems flag
17960
0
    if (!node->IsDockSpace())
17961
0
    {
17962
0
        host_window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
17963
0
        host_window->SkipItems = backup_skip_item;
17964
0
    }
17965
0
}
17966
17967
static void ImGui::DockNodeAddTabBar(ImGuiDockNode* node)
17968
0
{
17969
0
    IM_ASSERT(node->TabBar == NULL);
17970
0
    node->TabBar = IM_NEW(ImGuiTabBar);
17971
0
}
17972
17973
static void ImGui::DockNodeRemoveTabBar(ImGuiDockNode* node)
17974
0
{
17975
0
    if (node->TabBar == NULL)
17976
0
        return;
17977
0
    IM_DELETE(node->TabBar);
17978
0
    node->TabBar = NULL;
17979
0
}
17980
17981
static bool DockNodeIsDropAllowedOne(ImGuiWindow* payload, ImGuiWindow* host_window)
17982
0
{
17983
0
    if (host_window->DockNodeAsHost && host_window->DockNodeAsHost->IsDockSpace() && payload->BeginOrderWithinContext < host_window->BeginOrderWithinContext)
17984
0
        return false;
17985
17986
0
    ImGuiWindowClass* host_class = host_window->DockNodeAsHost ? &host_window->DockNodeAsHost->WindowClass : &host_window->WindowClass;
17987
0
    ImGuiWindowClass* payload_class = &payload->WindowClass;
17988
0
    if (host_class->ClassId != payload_class->ClassId)
17989
0
    {
17990
0
        bool pass = false;
17991
0
        if (host_class->ClassId != 0 && host_class->DockingAllowUnclassed && payload_class->ClassId == 0)
17992
0
            pass = true;
17993
0
        if (payload_class->ClassId != 0 && payload_class->DockingAllowUnclassed && host_class->ClassId == 0)
17994
0
            pass = true;
17995
0
        if (!pass)
17996
0
            return false;
17997
0
    }
17998
17999
    // Prevent docking any window created above a popup
18000
    // Technically we should support it (e.g. in the case of a long-lived modal window that had fancy docking features),
18001
    // by e.g. adding a 'if (!ImGui::IsWindowWithinBeginStackOf(host_window, popup_window))' test.
18002
    // But it would requires more work on our end because the dock host windows is technically created in NewFrame()
18003
    // and our ->ParentXXX and ->RootXXX pointers inside windows are currently mislading or lacking.
18004
0
    ImGuiContext& g = *GImGui;
18005
0
    for (int i = g.OpenPopupStack.Size - 1; i >= 0; i--)
18006
0
        if (ImGuiWindow* popup_window = g.OpenPopupStack[i].Window)
18007
0
            if (ImGui::IsWindowWithinBeginStackOf(payload, popup_window))   // Payload is created from within a popup begin stack.
18008
0
                return false;
18009
18010
0
    return true;
18011
0
}
18012
18013
static bool ImGui::DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* root_payload)
18014
0
{
18015
0
    if (root_payload->DockNodeAsHost && root_payload->DockNodeAsHost->IsSplitNode()) // FIXME-DOCK: Missing filtering
18016
0
        return true;
18017
18018
0
    const int payload_count = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows.Size : 1;
18019
0
    for (int payload_n = 0; payload_n < payload_count; payload_n++)
18020
0
    {
18021
0
        ImGuiWindow* payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows[payload_n] : root_payload;
18022
0
        if (DockNodeIsDropAllowedOne(payload, host_window))
18023
0
            return true;
18024
0
    }
18025
0
    return false;
18026
0
}
18027
18028
// window menu button == collapse button when not in a dock node.
18029
// FIXME: This is similar to RenderWindowTitleBarContents(), may want to share code.
18030
static void ImGui::DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos, ImVec2* out_close_button_pos)
18031
0
{
18032
0
    ImGuiContext& g = *GImGui;
18033
0
    ImGuiStyle& style = g.Style;
18034
18035
0
    ImRect r = ImRect(node->Pos.x, node->Pos.y, node->Pos.x + node->Size.x, node->Pos.y + g.FontSize + g.Style.FramePadding.y * 2.0f);
18036
0
    if (out_title_rect) { *out_title_rect = r; }
18037
18038
0
    r.Min.x += style.WindowBorderSize;
18039
0
    r.Max.x -= style.WindowBorderSize;
18040
18041
0
    float button_sz = g.FontSize;
18042
0
    r.Min.x += style.FramePadding.x;
18043
0
    r.Max.x -= style.FramePadding.x;
18044
0
    ImVec2 window_menu_button_pos = ImVec2(r.Min.x, r.Min.y + style.FramePadding.y);
18045
0
    if (node->HasCloseButton)
18046
0
    {
18047
0
        if (out_close_button_pos) *out_close_button_pos = ImVec2(r.Max.x - button_sz, r.Min.y + style.FramePadding.y);
18048
0
        r.Max.x -= button_sz + style.ItemInnerSpacing.x;
18049
0
    }
18050
0
    if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Left)
18051
0
    {
18052
0
        r.Min.x += button_sz + style.ItemInnerSpacing.x;
18053
0
    }
18054
0
    else if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Right)
18055
0
    {
18056
0
        window_menu_button_pos = ImVec2(r.Max.x - button_sz, r.Min.y + style.FramePadding.y);
18057
0
        r.Max.x -= button_sz + style.ItemInnerSpacing.x;
18058
0
    }
18059
0
    if (out_tab_bar_rect) { *out_tab_bar_rect = r; }
18060
0
    if (out_window_menu_button_pos) { *out_window_menu_button_pos = window_menu_button_pos; }
18061
0
}
18062
18063
void ImGui::DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired)
18064
0
{
18065
0
    ImGuiContext& g = *GImGui;
18066
0
    const float dock_spacing = g.Style.ItemInnerSpacing.x;
18067
0
    const ImGuiAxis axis = (dir == ImGuiDir_Left || dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
18068
0
    pos_new[axis ^ 1] = pos_old[axis ^ 1];
18069
0
    size_new[axis ^ 1] = size_old[axis ^ 1];
18070
18071
    // Distribute size on given axis (with a desired size or equally)
18072
0
    const float w_avail = size_old[axis] - dock_spacing;
18073
0
    if (size_new_desired[axis] > 0.0f && size_new_desired[axis] <= w_avail * 0.5f)
18074
0
    {
18075
0
        size_new[axis] = size_new_desired[axis];
18076
0
        size_old[axis] = IM_TRUNC(w_avail - size_new[axis]);
18077
0
    }
18078
0
    else
18079
0
    {
18080
0
        size_new[axis] = IM_TRUNC(w_avail * 0.5f);
18081
0
        size_old[axis] = IM_TRUNC(w_avail - size_new[axis]);
18082
0
    }
18083
18084
    // Position each node
18085
0
    if (dir == ImGuiDir_Right || dir == ImGuiDir_Down)
18086
0
    {
18087
0
        pos_new[axis] = pos_old[axis] + size_old[axis] + dock_spacing;
18088
0
    }
18089
0
    else if (dir == ImGuiDir_Left || dir == ImGuiDir_Up)
18090
0
    {
18091
0
        pos_new[axis] = pos_old[axis];
18092
0
        pos_old[axis] = pos_new[axis] + size_new[axis] + dock_spacing;
18093
0
    }
18094
0
}
18095
18096
// Retrieve the drop rectangles for a given direction or for the center + perform hit testing.
18097
bool ImGui::DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_r, bool outer_docking, ImVec2* test_mouse_pos)
18098
0
{
18099
0
    ImGuiContext& g = *GImGui;
18100
18101
0
    const float parent_smaller_axis = ImMin(parent.GetWidth(), parent.GetHeight());
18102
0
    const float hs_for_central_nodes = ImMin(g.FontSize * 1.5f, ImMax(g.FontSize * 0.5f, parent_smaller_axis / 8.0f));
18103
0
    float hs_w; // Half-size, longer axis
18104
0
    float hs_h; // Half-size, smaller axis
18105
0
    ImVec2 off; // Distance from edge or center
18106
0
    if (outer_docking)
18107
0
    {
18108
        //hs_w = ImTrunc(ImClamp(parent_smaller_axis - hs_for_central_nodes * 4.0f, g.FontSize * 0.5f, g.FontSize * 8.0f));
18109
        //hs_h = ImTrunc(hs_w * 0.15f);
18110
        //off = ImVec2(ImTrunc(parent.GetWidth() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h), ImTrunc(parent.GetHeight() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h));
18111
0
        hs_w = ImTrunc(hs_for_central_nodes * 1.50f);
18112
0
        hs_h = ImTrunc(hs_for_central_nodes * 0.80f);
18113
0
        off = ImTrunc(ImVec2(parent.GetWidth() * 0.5f - hs_h, parent.GetHeight() * 0.5f - hs_h));
18114
0
    }
18115
0
    else
18116
0
    {
18117
0
        hs_w = ImTrunc(hs_for_central_nodes);
18118
0
        hs_h = ImTrunc(hs_for_central_nodes * 0.90f);
18119
0
        off = ImTrunc(ImVec2(hs_w * 2.40f, hs_w * 2.40f));
18120
0
    }
18121
18122
0
    ImVec2 c = ImTrunc(parent.GetCenter());
18123
0
    if      (dir == ImGuiDir_None)  { out_r = ImRect(c.x - hs_w, c.y - hs_w,         c.x + hs_w, c.y + hs_w);         }
18124
0
    else if (dir == ImGuiDir_Up)    { out_r = ImRect(c.x - hs_w, c.y - off.y - hs_h, c.x + hs_w, c.y - off.y + hs_h); }
18125
0
    else if (dir == ImGuiDir_Down)  { out_r = ImRect(c.x - hs_w, c.y + off.y - hs_h, c.x + hs_w, c.y + off.y + hs_h); }
18126
0
    else if (dir == ImGuiDir_Left)  { out_r = ImRect(c.x - off.x - hs_h, c.y - hs_w, c.x - off.x + hs_h, c.y + hs_w); }
18127
0
    else if (dir == ImGuiDir_Right) { out_r = ImRect(c.x + off.x - hs_h, c.y - hs_w, c.x + off.x + hs_h, c.y + hs_w); }
18128
18129
0
    if (test_mouse_pos == NULL)
18130
0
        return false;
18131
18132
0
    ImRect hit_r = out_r;
18133
0
    if (!outer_docking)
18134
0
    {
18135
        // Custom hit testing for the 5-way selection, designed to reduce flickering when moving diagonally between sides
18136
0
        hit_r.Expand(ImTrunc(hs_w * 0.30f));
18137
0
        ImVec2 mouse_delta = (*test_mouse_pos - c);
18138
0
        float mouse_delta_len2 = ImLengthSqr(mouse_delta);
18139
0
        float r_threshold_center = hs_w * 1.4f;
18140
0
        float r_threshold_sides = hs_w * (1.4f + 1.2f);
18141
0
        if (mouse_delta_len2 < r_threshold_center * r_threshold_center)
18142
0
            return (dir == ImGuiDir_None);
18143
0
        if (mouse_delta_len2 < r_threshold_sides * r_threshold_sides)
18144
0
            return (dir == ImGetDirQuadrantFromDelta(mouse_delta.x, mouse_delta.y));
18145
0
    }
18146
0
    return hit_r.Contains(*test_mouse_pos);
18147
0
}
18148
18149
// host_node may be NULL if the window doesn't have a DockNode already.
18150
// FIXME-DOCK: This is misnamed since it's also doing the filtering.
18151
static void ImGui::DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDockPreviewData* data, bool is_explicit_target, bool is_outer_docking)
18152
0
{
18153
0
    ImGuiContext& g = *GImGui;
18154
18155
    // There is an edge case when docking into a dockspace which only has inactive nodes.
18156
    // In this case DockNodeTreeFindNodeByPos() will have selected a leaf node which is inactive.
18157
    // Because the inactive leaf node doesn't have proper pos/size yet, we'll use the root node as reference.
18158
0
    if (payload_node == NULL)
18159
0
        payload_node = payload_window->DockNodeAsHost;
18160
0
    ImGuiDockNode* ref_node_for_rect = (host_node && !host_node->IsVisible) ? DockNodeGetRootNode(host_node) : host_node;
18161
0
    if (ref_node_for_rect)
18162
0
        IM_ASSERT(ref_node_for_rect->IsVisible == true);
18163
18164
    // Filter, figure out where we are allowed to dock
18165
0
    ImGuiDockNodeFlags src_node_flags = payload_node ? payload_node->MergedFlags : payload_window->WindowClass.DockNodeFlagsOverrideSet;
18166
0
    ImGuiDockNodeFlags dst_node_flags = host_node ? host_node->MergedFlags : host_window->WindowClass.DockNodeFlagsOverrideSet;
18167
0
    data->IsCenterAvailable = true;
18168
0
    if (is_outer_docking)
18169
0
        data->IsCenterAvailable = false;
18170
0
    else if (dst_node_flags & ImGuiDockNodeFlags_NoDockingOverMe)
18171
0
        data->IsCenterAvailable = false;
18172
0
    else if (host_node && (dst_node_flags & ImGuiDockNodeFlags_NoDockingOverCentralNode) && host_node->IsCentralNode())
18173
0
        data->IsCenterAvailable = false;
18174
0
    else if ((!host_node || !host_node->IsEmpty()) && payload_node && payload_node->IsSplitNode() && (payload_node->OnlyNodeWithWindows == NULL)) // Is _visibly_ split?
18175
0
        data->IsCenterAvailable = false;
18176
0
    else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverOther) && (!host_node || !host_node->IsEmpty()))
18177
0
        data->IsCenterAvailable = false;
18178
0
    else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverEmpty) && host_node && host_node->IsEmpty())
18179
0
        data->IsCenterAvailable = false;
18180
18181
0
    data->IsSidesAvailable = true;
18182
0
    if ((dst_node_flags & ImGuiDockNodeFlags_NoDockingSplit) || g.IO.ConfigDockingNoSplit)
18183
0
        data->IsSidesAvailable = false;
18184
0
    else if (!is_outer_docking && host_node && host_node->ParentNode == NULL && host_node->IsCentralNode())
18185
0
        data->IsSidesAvailable = false;
18186
0
    else if (src_node_flags & ImGuiDockNodeFlags_NoDockingSplitOther)
18187
0
        data->IsSidesAvailable = false;
18188
18189
    // Build a tentative future node (reuse same structure because it is practical. Shape will be readjusted when previewing a split)
18190
0
    data->FutureNode.HasCloseButton = (host_node ? host_node->HasCloseButton : host_window->HasCloseButton) || (payload_window->HasCloseButton);
18191
0
    data->FutureNode.HasWindowMenuButton = host_node ? true : ((host_window->Flags & ImGuiWindowFlags_NoCollapse) == 0);
18192
0
    data->FutureNode.Pos = ref_node_for_rect ? ref_node_for_rect->Pos : host_window->Pos;
18193
0
    data->FutureNode.Size = ref_node_for_rect ? ref_node_for_rect->Size : host_window->Size;
18194
18195
    // Calculate drop shapes geometry for allowed splitting directions
18196
0
    IM_ASSERT(ImGuiDir_None == -1);
18197
0
    data->SplitNode = host_node;
18198
0
    data->SplitDir = ImGuiDir_None;
18199
0
    data->IsSplitDirExplicit = false;
18200
0
    if (!host_window->Collapsed)
18201
0
        for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
18202
0
        {
18203
0
            if (dir == ImGuiDir_None && !data->IsCenterAvailable)
18204
0
                continue;
18205
0
            if (dir != ImGuiDir_None && !data->IsSidesAvailable)
18206
0
                continue;
18207
0
            if (DockNodeCalcDropRectsAndTestMousePos(data->FutureNode.Rect(), (ImGuiDir)dir, data->DropRectsDraw[dir+1], is_outer_docking, &g.IO.MousePos))
18208
0
            {
18209
0
                data->SplitDir = (ImGuiDir)dir;
18210
0
                data->IsSplitDirExplicit = true;
18211
0
            }
18212
0
        }
18213
18214
    // When docking without holding Shift, we only allow and preview docking when hovering over a drop rect or over the title bar
18215
0
    data->IsDropAllowed = (data->SplitDir != ImGuiDir_None) || (data->IsCenterAvailable);
18216
0
    if (!is_explicit_target && !data->IsSplitDirExplicit && !g.IO.ConfigDockingWithShift)
18217
0
        data->IsDropAllowed = false;
18218
18219
    // Calculate split area
18220
0
    data->SplitRatio = 0.0f;
18221
0
    if (data->SplitDir != ImGuiDir_None)
18222
0
    {
18223
0
        ImGuiDir split_dir = data->SplitDir;
18224
0
        ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
18225
0
        ImVec2 pos_new, pos_old = data->FutureNode.Pos;
18226
0
        ImVec2 size_new, size_old = data->FutureNode.Size;
18227
0
        DockNodeCalcSplitRects(pos_old, size_old, pos_new, size_new, split_dir, payload_window->Size);
18228
18229
        // Calculate split ratio so we can pass it down the docking request
18230
0
        float split_ratio = ImSaturate(size_new[split_axis] / data->FutureNode.Size[split_axis]);
18231
0
        data->FutureNode.Pos = pos_new;
18232
0
        data->FutureNode.Size = size_new;
18233
0
        data->SplitRatio = (split_dir == ImGuiDir_Right || split_dir == ImGuiDir_Down) ? (1.0f - split_ratio) : (split_ratio);
18234
0
    }
18235
0
}
18236
18237
static void ImGui::DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* root_payload, const ImGuiDockPreviewData* data)
18238
0
{
18239
0
    ImGuiContext& g = *GImGui;
18240
0
    IM_ASSERT(g.CurrentWindow == host_window);   // Because we rely on font size to calculate tab sizes
18241
18242
    // With this option, we only display the preview on the target viewport, and the payload viewport is made transparent.
18243
    // To compensate for the single layer obstructed by the payload, we'll increase the alpha of the preview nodes.
18244
0
    const bool is_transparent_payload = g.IO.ConfigDockingTransparentPayload;
18245
18246
    // In case the two windows involved are on different viewports, we will draw the overlay on each of them.
18247
0
    int overlay_draw_lists_count = 0;
18248
0
    ImDrawList* overlay_draw_lists[2];
18249
0
    overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(host_window->Viewport);
18250
0
    if (host_window->Viewport != root_payload->Viewport && !is_transparent_payload)
18251
0
        overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(root_payload->Viewport);
18252
18253
    // Draw main preview rectangle
18254
0
    const ImU32 overlay_col_main = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.60f : 0.40f);
18255
0
    const ImU32 overlay_col_drop = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.90f : 0.70f);
18256
0
    const ImU32 overlay_col_drop_hovered = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 1.20f : 1.00f);
18257
0
    const ImU32 overlay_col_lines = GetColorU32(ImGuiCol_NavWindowingHighlight, is_transparent_payload ? 0.80f : 0.60f);
18258
18259
    // Display area preview
18260
0
    const bool can_preview_tabs = (root_payload->DockNodeAsHost == NULL || root_payload->DockNodeAsHost->Windows.Size > 0);
18261
0
    if (data->IsDropAllowed)
18262
0
    {
18263
0
        ImRect overlay_rect = data->FutureNode.Rect();
18264
0
        if (data->SplitDir == ImGuiDir_None && can_preview_tabs)
18265
0
            overlay_rect.Min.y += GetFrameHeight();
18266
0
        if (data->SplitDir != ImGuiDir_None || data->IsCenterAvailable)
18267
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
18268
0
                overlay_draw_lists[overlay_n]->AddRectFilled(overlay_rect.Min, overlay_rect.Max, overlay_col_main, host_window->WindowRounding, CalcRoundingFlagsForRectInRect(overlay_rect, host_window->Rect(), g.Style.DockingSeparatorSize));
18269
0
    }
18270
18271
    // Display tab shape/label preview unless we are splitting node (it generally makes the situation harder to read)
18272
0
    if (data->IsDropAllowed && can_preview_tabs && data->SplitDir == ImGuiDir_None && data->IsCenterAvailable)
18273
0
    {
18274
        // Compute target tab bar geometry so we can locate our preview tabs
18275
0
        ImRect tab_bar_rect;
18276
0
        DockNodeCalcTabBarLayout(&data->FutureNode, NULL, &tab_bar_rect, NULL, NULL);
18277
0
        ImVec2 tab_pos = tab_bar_rect.Min;
18278
0
        if (host_node && host_node->TabBar)
18279
0
        {
18280
0
            if (!host_node->IsHiddenTabBar() && !host_node->IsNoTabBar())
18281
0
                tab_pos.x += host_node->TabBar->WidthAllTabs + g.Style.ItemInnerSpacing.x; // We don't use OffsetNewTab because when using non-persistent-order tab bar it is incremented with each Tab submission.
18282
0
            else
18283
0
                tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_node->Windows[0]).x;
18284
0
        }
18285
0
        else if (!(host_window->Flags & ImGuiWindowFlags_DockNodeHost))
18286
0
        {
18287
0
            tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_window).x; // Account for slight offset which will be added when changing from title bar to tab bar
18288
0
        }
18289
18290
        // Draw tab shape/label preview (payload may be a loose window or a host window carrying multiple tabbed windows)
18291
0
        if (root_payload->DockNodeAsHost)
18292
0
            IM_ASSERT(root_payload->DockNodeAsHost->Windows.Size <= root_payload->DockNodeAsHost->TabBar->Tabs.Size);
18293
0
        ImGuiTabBar* tab_bar_with_payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->TabBar : NULL;
18294
0
        const int payload_count = tab_bar_with_payload ? tab_bar_with_payload->Tabs.Size : 1;
18295
0
        for (int payload_n = 0; payload_n < payload_count; payload_n++)
18296
0
        {
18297
            // DockNode's TabBar may have non-window Tabs manually appended by user
18298
0
            ImGuiWindow* payload_window = tab_bar_with_payload ? tab_bar_with_payload->Tabs[payload_n].Window : root_payload;
18299
0
            if (tab_bar_with_payload && payload_window == NULL)
18300
0
                continue;
18301
0
            if (!DockNodeIsDropAllowedOne(payload_window, host_window))
18302
0
                continue;
18303
18304
            // Calculate the tab bounding box for each payload window
18305
0
            ImVec2 tab_size = TabItemCalcSize(payload_window);
18306
0
            ImRect tab_bb(tab_pos.x, tab_pos.y, tab_pos.x + tab_size.x, tab_pos.y + tab_size.y);
18307
0
            tab_pos.x += tab_size.x + g.Style.ItemInnerSpacing.x;
18308
0
            const ImU32 overlay_col_text = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_Text]);
18309
0
            const ImU32 overlay_col_tabs = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_TabSelected]);
18310
0
            PushStyleColor(ImGuiCol_Text, overlay_col_text);
18311
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
18312
0
            {
18313
0
                ImGuiTabItemFlags tab_flags = (payload_window->Flags & ImGuiWindowFlags_UnsavedDocument) ? ImGuiTabItemFlags_UnsavedDocument : 0;
18314
0
                if (!tab_bar_rect.Contains(tab_bb))
18315
0
                    overlay_draw_lists[overlay_n]->PushClipRect(tab_bar_rect.Min, tab_bar_rect.Max);
18316
0
                TabItemBackground(overlay_draw_lists[overlay_n], tab_bb, tab_flags, overlay_col_tabs);
18317
0
                TabItemLabelAndCloseButton(overlay_draw_lists[overlay_n], tab_bb, tab_flags, g.Style.FramePadding, payload_window->Name, 0, 0, false, NULL, NULL);
18318
0
                if (!tab_bar_rect.Contains(tab_bb))
18319
0
                    overlay_draw_lists[overlay_n]->PopClipRect();
18320
0
            }
18321
0
            PopStyleColor();
18322
0
        }
18323
0
    }
18324
18325
    // Display drop boxes
18326
0
    const float overlay_rounding = ImMax(3.0f, g.Style.FrameRounding);
18327
0
    for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
18328
0
    {
18329
0
        if (!data->DropRectsDraw[dir + 1].IsInverted())
18330
0
        {
18331
0
            ImRect draw_r = data->DropRectsDraw[dir + 1];
18332
0
            ImRect draw_r_in = draw_r;
18333
0
            draw_r_in.Expand(-2.0f);
18334
0
            ImU32 overlay_col = (data->SplitDir == (ImGuiDir)dir && data->IsSplitDirExplicit) ? overlay_col_drop_hovered : overlay_col_drop;
18335
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
18336
0
            {
18337
0
                ImVec2 center = ImFloor(draw_r_in.GetCenter());
18338
0
                overlay_draw_lists[overlay_n]->AddRectFilled(draw_r.Min, draw_r.Max, overlay_col, overlay_rounding);
18339
0
                overlay_draw_lists[overlay_n]->AddRect(draw_r_in.Min, draw_r_in.Max, overlay_col_lines, overlay_rounding);
18340
0
                if (dir == ImGuiDir_Left || dir == ImGuiDir_Right)
18341
0
                    overlay_draw_lists[overlay_n]->AddLine(ImVec2(center.x, draw_r_in.Min.y), ImVec2(center.x, draw_r_in.Max.y), overlay_col_lines);
18342
0
                if (dir == ImGuiDir_Up || dir == ImGuiDir_Down)
18343
0
                    overlay_draw_lists[overlay_n]->AddLine(ImVec2(draw_r_in.Min.x, center.y), ImVec2(draw_r_in.Max.x, center.y), overlay_col_lines);
18344
0
            }
18345
0
        }
18346
18347
        // Stop after ImGuiDir_None
18348
0
        if ((host_node && (host_node->MergedFlags & ImGuiDockNodeFlags_NoDockingSplit)) || g.IO.ConfigDockingNoSplit)
18349
0
            return;
18350
0
    }
18351
0
}
18352
18353
//-----------------------------------------------------------------------------
18354
// Docking: ImGuiDockNode Tree manipulation functions
18355
//-----------------------------------------------------------------------------
18356
// - DockNodeTreeSplit()
18357
// - DockNodeTreeMerge()
18358
// - DockNodeTreeUpdatePosSize()
18359
// - DockNodeTreeUpdateSplitterFindTouchingNode()
18360
// - DockNodeTreeUpdateSplitter()
18361
// - DockNodeTreeFindFallbackLeafNode()
18362
// - DockNodeTreeFindNodeByPos()
18363
//-----------------------------------------------------------------------------
18364
18365
void ImGui::DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_inheritor_child_idx, float split_ratio, ImGuiDockNode* new_node)
18366
0
{
18367
0
    ImGuiContext& g = *GImGui;
18368
0
    IM_ASSERT(split_axis != ImGuiAxis_None);
18369
18370
0
    ImGuiDockNode* child_0 = (new_node && split_inheritor_child_idx != 0) ? new_node : DockContextAddNode(ctx, 0);
18371
0
    child_0->ParentNode = parent_node;
18372
18373
0
    ImGuiDockNode* child_1 = (new_node && split_inheritor_child_idx != 1) ? new_node : DockContextAddNode(ctx, 0);
18374
0
    child_1->ParentNode = parent_node;
18375
18376
0
    ImGuiDockNode* child_inheritor = (split_inheritor_child_idx == 0) ? child_0 : child_1;
18377
0
    DockNodeMoveChildNodes(child_inheritor, parent_node);
18378
0
    parent_node->ChildNodes[0] = child_0;
18379
0
    parent_node->ChildNodes[1] = child_1;
18380
0
    parent_node->ChildNodes[split_inheritor_child_idx]->VisibleWindow = parent_node->VisibleWindow;
18381
0
    parent_node->SplitAxis = split_axis;
18382
0
    parent_node->VisibleWindow = NULL;
18383
0
    parent_node->AuthorityForPos = parent_node->AuthorityForSize = ImGuiDataAuthority_DockNode;
18384
18385
0
    float size_avail = (parent_node->Size[split_axis] - g.Style.DockingSeparatorSize);
18386
0
    size_avail = ImMax(size_avail, g.Style.WindowMinSize[split_axis] * 2.0f);
18387
0
    IM_ASSERT(size_avail > 0.0f); // If you created a node manually with DockBuilderAddNode(), you need to also call DockBuilderSetNodeSize() before splitting.
18388
0
    child_0->SizeRef = child_1->SizeRef = parent_node->Size;
18389
0
    child_0->SizeRef[split_axis] = ImTrunc(size_avail * split_ratio);
18390
0
    child_1->SizeRef[split_axis] = ImTrunc(size_avail - child_0->SizeRef[split_axis]);
18391
18392
0
    DockNodeMoveWindows(parent_node->ChildNodes[split_inheritor_child_idx], parent_node);
18393
0
    DockSettingsRenameNodeReferences(parent_node->ID, parent_node->ChildNodes[split_inheritor_child_idx]->ID);
18394
0
    DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(parent_node));
18395
0
    DockNodeTreeUpdatePosSize(parent_node, parent_node->Pos, parent_node->Size);
18396
18397
    // Flags transfer (e.g. this is where we transfer the ImGuiDockNodeFlags_CentralNode property)
18398
0
    child_0->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
18399
0
    child_1->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
18400
0
    child_inheritor->LocalFlags = parent_node->LocalFlags & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
18401
0
    parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_;
18402
0
    child_0->UpdateMergedFlags();
18403
0
    child_1->UpdateMergedFlags();
18404
0
    parent_node->UpdateMergedFlags();
18405
0
    if (child_inheritor->IsCentralNode())
18406
0
        DockNodeGetRootNode(parent_node)->CentralNode = child_inheritor;
18407
0
}
18408
18409
void ImGui::DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child)
18410
0
{
18411
    // When called from DockContextProcessUndockNode() it is possible that one of the child is NULL.
18412
0
    ImGuiContext& g = *GImGui;
18413
0
    ImGuiDockNode* child_0 = parent_node->ChildNodes[0];
18414
0
    ImGuiDockNode* child_1 = parent_node->ChildNodes[1];
18415
0
    IM_ASSERT(child_0 || child_1);
18416
0
    IM_ASSERT(merge_lead_child == child_0 || merge_lead_child == child_1);
18417
0
    if ((child_0 && child_0->Windows.Size > 0) || (child_1 && child_1->Windows.Size > 0))
18418
0
    {
18419
0
        IM_ASSERT(parent_node->TabBar == NULL);
18420
0
        IM_ASSERT(parent_node->Windows.Size == 0);
18421
0
    }
18422
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeTreeMerge: 0x%08X + 0x%08X back into parent 0x%08X\n", child_0 ? child_0->ID : 0, child_1 ? child_1->ID : 0, parent_node->ID);
18423
18424
0
    ImVec2 backup_last_explicit_size = parent_node->SizeRef;
18425
0
    DockNodeMoveChildNodes(parent_node, merge_lead_child);
18426
0
    if (child_0)
18427
0
    {
18428
0
        DockNodeMoveWindows(parent_node, child_0); // Generally only 1 of the 2 child node will have windows
18429
0
        DockSettingsRenameNodeReferences(child_0->ID, parent_node->ID);
18430
0
    }
18431
0
    if (child_1)
18432
0
    {
18433
0
        DockNodeMoveWindows(parent_node, child_1);
18434
0
        DockSettingsRenameNodeReferences(child_1->ID, parent_node->ID);
18435
0
    }
18436
0
    DockNodeApplyPosSizeToWindows(parent_node);
18437
0
    parent_node->AuthorityForPos = parent_node->AuthorityForSize = parent_node->AuthorityForViewport = ImGuiDataAuthority_Auto;
18438
0
    parent_node->VisibleWindow = merge_lead_child->VisibleWindow;
18439
0
    parent_node->SizeRef = backup_last_explicit_size;
18440
18441
    // Flags transfer
18442
0
    parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_; // Preserve Dockspace flag
18443
0
    parent_node->LocalFlags |= (child_0 ? child_0->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
18444
0
    parent_node->LocalFlags |= (child_1 ? child_1->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
18445
0
    parent_node->LocalFlagsInWindows = (child_0 ? child_0->LocalFlagsInWindows : 0) | (child_1 ? child_1->LocalFlagsInWindows : 0); // FIXME: Would be more consistent to update from actual windows
18446
0
    parent_node->UpdateMergedFlags();
18447
18448
0
    if (child_0)
18449
0
    {
18450
0
        ctx->DockContext.Nodes.SetVoidPtr(child_0->ID, NULL);
18451
0
        IM_DELETE(child_0);
18452
0
    }
18453
0
    if (child_1)
18454
0
    {
18455
0
        ctx->DockContext.Nodes.SetVoidPtr(child_1->ID, NULL);
18456
0
        IM_DELETE(child_1);
18457
0
    }
18458
0
}
18459
18460
// Update Pos/Size for a node hierarchy (don't affect child Windows yet)
18461
// (Depth-first, Pre-Order)
18462
void ImGui::DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node)
18463
0
{
18464
    // During the regular dock node update we write to all nodes.
18465
    // 'only_write_to_single_node' is only set when turning a node visible mid-frame and we need its size right-away.
18466
0
    ImGuiContext& g = *GImGui;
18467
0
    const bool write_to_node = only_write_to_single_node == NULL || only_write_to_single_node == node;
18468
0
    if (write_to_node)
18469
0
    {
18470
0
        node->Pos = pos;
18471
0
        node->Size = size;
18472
0
    }
18473
18474
0
    if (node->IsLeafNode())
18475
0
        return;
18476
18477
0
    ImGuiDockNode* child_0 = node->ChildNodes[0];
18478
0
    ImGuiDockNode* child_1 = node->ChildNodes[1];
18479
0
    ImVec2 child_0_pos = pos, child_1_pos = pos;
18480
0
    ImVec2 child_0_size = size, child_1_size = size;
18481
18482
0
    const bool child_0_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_0));
18483
0
    const bool child_1_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_1));
18484
0
    const bool child_0_is_or_will_be_visible = child_0->IsVisible || child_0_is_toward_single_node;
18485
0
    const bool child_1_is_or_will_be_visible = child_1->IsVisible || child_1_is_toward_single_node;
18486
18487
0
    if (child_0_is_or_will_be_visible && child_1_is_or_will_be_visible)
18488
0
    {
18489
0
        const float spacing = g.Style.DockingSeparatorSize;
18490
0
        const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
18491
0
        const float size_avail = ImMax(size[axis] - spacing, 0.0f);
18492
18493
        // Size allocation policy
18494
        // 1) The first 0..WindowMinSize[axis]*2 are allocated evenly to both windows.
18495
0
        const float size_min_each = ImTrunc(ImMin(size_avail, g.Style.WindowMinSize[axis] * 2.0f) * 0.5f);
18496
18497
        // FIXME: Blocks 2) and 3) are essentially doing nearly the same thing.
18498
        // Difference are: write-back to SizeRef; application of a minimum size; rounding before ImTrunc()
18499
        // Clarify and rework differences between Size & SizeRef and purpose of WantLockSizeOnce
18500
18501
        // 2) Process locked absolute size (during a splitter resize we preserve the child of nodes not touching the splitter edge)
18502
0
        if (child_0->WantLockSizeOnce && !child_1->WantLockSizeOnce)
18503
0
        {
18504
0
            child_0_size[axis] = child_0->SizeRef[axis] = ImMin(size_avail - 1.0f, child_0->Size[axis]);
18505
0
            child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
18506
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
18507
0
        }
18508
0
        else if (child_1->WantLockSizeOnce && !child_0->WantLockSizeOnce)
18509
0
        {
18510
0
            child_1_size[axis] = child_1->SizeRef[axis] = ImMin(size_avail - 1.0f, child_1->Size[axis]);
18511
0
            child_0_size[axis] = child_0->SizeRef[axis] = (size_avail - child_1_size[axis]);
18512
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
18513
0
        }
18514
0
        else if (child_0->WantLockSizeOnce && child_1->WantLockSizeOnce)
18515
0
        {
18516
            // FIXME-DOCK: We cannot honor the requested size, so apply ratio.
18517
            // Currently this path will only be taken if code programmatically sets WantLockSizeOnce
18518
0
            float split_ratio = child_0_size[axis] / (child_0_size[axis] + child_1_size[axis]);
18519
0
            child_0_size[axis] = child_0->SizeRef[axis] = ImTrunc(size_avail * split_ratio);
18520
0
            child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
18521
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
18522
0
        }
18523
18524
        // 3) If one window is the central node (~ use remaining space, should be made explicit!), use explicit size from the other, and remainder for the central node
18525
0
        else if (child_0->SizeRef[axis] != 0.0f && child_1->HasCentralNodeChild)
18526
0
        {
18527
0
            child_0_size[axis] = ImMin(size_avail - size_min_each, child_0->SizeRef[axis]);
18528
0
            child_1_size[axis] = (size_avail - child_0_size[axis]);
18529
0
        }
18530
0
        else if (child_1->SizeRef[axis] != 0.0f && child_0->HasCentralNodeChild)
18531
0
        {
18532
0
            child_1_size[axis] = ImMin(size_avail - size_min_each, child_1->SizeRef[axis]);
18533
0
            child_0_size[axis] = (size_avail - child_1_size[axis]);
18534
0
        }
18535
0
        else
18536
0
        {
18537
            // 4) Otherwise distribute according to the relative ratio of each SizeRef value
18538
0
            float split_ratio = child_0->SizeRef[axis] / (child_0->SizeRef[axis] + child_1->SizeRef[axis]);
18539
0
            child_0_size[axis] = ImMax(size_min_each, ImTrunc(size_avail * split_ratio + 0.5f));
18540
0
            child_1_size[axis] = (size_avail - child_0_size[axis]);
18541
0
        }
18542
18543
0
        child_1_pos[axis] += spacing + child_0_size[axis];
18544
0
    }
18545
18546
0
    if (only_write_to_single_node == NULL)
18547
0
        child_0->WantLockSizeOnce = child_1->WantLockSizeOnce = false;
18548
18549
0
    const bool child_0_recurse = only_write_to_single_node ? child_0_is_toward_single_node : child_0->IsVisible;
18550
0
    const bool child_1_recurse = only_write_to_single_node ? child_1_is_toward_single_node : child_1->IsVisible;
18551
0
    if (child_0_recurse)
18552
0
        DockNodeTreeUpdatePosSize(child_0, child_0_pos, child_0_size);
18553
0
    if (child_1_recurse)
18554
0
        DockNodeTreeUpdatePosSize(child_1, child_1_pos, child_1_size);
18555
0
}
18556
18557
static void DockNodeTreeUpdateSplitterFindTouchingNode(ImGuiDockNode* node, ImGuiAxis axis, int side, ImVector<ImGuiDockNode*>* touching_nodes)
18558
0
{
18559
0
    if (node->IsLeafNode())
18560
0
    {
18561
0
        touching_nodes->push_back(node);
18562
0
        return;
18563
0
    }
18564
0
    if (node->ChildNodes[0]->IsVisible)
18565
0
        if (node->SplitAxis != axis || side == 0 || !node->ChildNodes[1]->IsVisible)
18566
0
            DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[0], axis, side, touching_nodes);
18567
0
    if (node->ChildNodes[1]->IsVisible)
18568
0
        if (node->SplitAxis != axis || side == 1 || !node->ChildNodes[0]->IsVisible)
18569
0
            DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[1], axis, side, touching_nodes);
18570
0
}
18571
18572
// (Depth-First, Pre-Order)
18573
void ImGui::DockNodeTreeUpdateSplitter(ImGuiDockNode* node)
18574
0
{
18575
0
    if (node->IsLeafNode())
18576
0
        return;
18577
18578
0
    ImGuiContext& g = *GImGui;
18579
18580
0
    ImGuiDockNode* child_0 = node->ChildNodes[0];
18581
0
    ImGuiDockNode* child_1 = node->ChildNodes[1];
18582
0
    if (child_0->IsVisible && child_1->IsVisible)
18583
0
    {
18584
        // Bounding box of the splitter cover the space between both nodes (w = Spacing, h = Size[xy^1] for when splitting horizontally)
18585
0
        const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
18586
0
        IM_ASSERT(axis != ImGuiAxis_None);
18587
0
        ImRect bb;
18588
0
        bb.Min = child_0->Pos;
18589
0
        bb.Max = child_1->Pos;
18590
0
        bb.Min[axis] += child_0->Size[axis];
18591
0
        bb.Max[axis ^ 1] += child_1->Size[axis ^ 1];
18592
        //if (g.IO.KeyCtrl) GetForegroundDrawList(g.CurrentWindow->Viewport)->AddRect(bb.Min, bb.Max, IM_COL32(255,0,255,255));
18593
18594
0
        const ImGuiDockNodeFlags merged_flags = child_0->MergedFlags | child_1->MergedFlags; // Merged flags for BOTH childs
18595
0
        const ImGuiDockNodeFlags no_resize_axis_flag = (axis == ImGuiAxis_X) ? ImGuiDockNodeFlags_NoResizeX : ImGuiDockNodeFlags_NoResizeY;
18596
0
        if ((merged_flags & ImGuiDockNodeFlags_NoResize) || (merged_flags & no_resize_axis_flag))
18597
0
        {
18598
0
            ImGuiWindow* window = g.CurrentWindow;
18599
0
            window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Separator), g.Style.FrameRounding);
18600
0
        }
18601
0
        else
18602
0
        {
18603
            //bb.Min[axis] += 1; // Display a little inward so highlight doesn't connect with nearby tabs on the neighbor node.
18604
            //bb.Max[axis] -= 1;
18605
0
            PushID(node->ID);
18606
18607
            // Find resizing limits by gathering list of nodes that are touching the splitter line.
18608
0
            ImVector<ImGuiDockNode*> touching_nodes[2];
18609
0
            float min_size = g.Style.WindowMinSize[axis];
18610
0
            float resize_limits[2];
18611
0
            resize_limits[0] = node->ChildNodes[0]->Pos[axis] + min_size;
18612
0
            resize_limits[1] = node->ChildNodes[1]->Pos[axis] + node->ChildNodes[1]->Size[axis] - min_size;
18613
18614
0
            ImGuiID splitter_id = GetID("##Splitter");
18615
0
            if (g.ActiveId == splitter_id) // Only process when splitter is active
18616
0
            {
18617
0
                DockNodeTreeUpdateSplitterFindTouchingNode(child_0, axis, 1, &touching_nodes[0]);
18618
0
                DockNodeTreeUpdateSplitterFindTouchingNode(child_1, axis, 0, &touching_nodes[1]);
18619
0
                for (int touching_node_n = 0; touching_node_n < touching_nodes[0].Size; touching_node_n++)
18620
0
                    resize_limits[0] = ImMax(resize_limits[0], touching_nodes[0][touching_node_n]->Rect().Min[axis] + min_size);
18621
0
                for (int touching_node_n = 0; touching_node_n < touching_nodes[1].Size; touching_node_n++)
18622
0
                    resize_limits[1] = ImMin(resize_limits[1], touching_nodes[1][touching_node_n]->Rect().Max[axis] - min_size);
18623
18624
                // [DEBUG] Render touching nodes & limits
18625
                /*
18626
                ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
18627
                for (int n = 0; n < 2; n++)
18628
                {
18629
                    for (int touching_node_n = 0; touching_node_n < touching_nodes[n].Size; touching_node_n++)
18630
                        draw_list->AddRect(touching_nodes[n][touching_node_n]->Pos, touching_nodes[n][touching_node_n]->Pos + touching_nodes[n][touching_node_n]->Size, IM_COL32(0, 255, 0, 255));
18631
                    if (axis == ImGuiAxis_X)
18632
                        draw_list->AddLine(ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y), ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y + node->ChildNodes[n]->Size.y), IM_COL32(255, 0, 255, 255), 3.0f);
18633
                    else
18634
                        draw_list->AddLine(ImVec2(node->ChildNodes[n]->Pos.x, resize_limits[n]), ImVec2(node->ChildNodes[n]->Pos.x + node->ChildNodes[n]->Size.x, resize_limits[n]), IM_COL32(255, 0, 255, 255), 3.0f);
18635
                }
18636
                */
18637
0
            }
18638
18639
            // Use a short delay before highlighting the splitter (and changing the mouse cursor) in order for regular mouse movement to not highlight many splitters
18640
0
            float cur_size_0 = child_0->Size[axis];
18641
0
            float cur_size_1 = child_1->Size[axis];
18642
0
            float min_size_0 = resize_limits[0] - child_0->Pos[axis];
18643
0
            float min_size_1 = child_1->Pos[axis] + child_1->Size[axis] - resize_limits[1];
18644
0
            ImU32 bg_col = GetColorU32(ImGuiCol_WindowBg);
18645
0
            if (SplitterBehavior(bb, GetID("##Splitter"), axis, &cur_size_0, &cur_size_1, min_size_0, min_size_1, WINDOWS_HOVER_PADDING, WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER, bg_col))
18646
0
            {
18647
0
                if (touching_nodes[0].Size > 0 && touching_nodes[1].Size > 0)
18648
0
                {
18649
0
                    child_0->Size[axis] = child_0->SizeRef[axis] = cur_size_0;
18650
0
                    child_1->Pos[axis] -= cur_size_1 - child_1->Size[axis];
18651
0
                    child_1->Size[axis] = child_1->SizeRef[axis] = cur_size_1;
18652
18653
                    // Lock the size of every node that is a sibling of the node we are touching
18654
                    // This might be less desirable if we can merge sibling of a same axis into the same parental level.
18655
0
                    for (int side_n = 0; side_n < 2; side_n++)
18656
0
                        for (int touching_node_n = 0; touching_node_n < touching_nodes[side_n].Size; touching_node_n++)
18657
0
                        {
18658
0
                            ImGuiDockNode* touching_node = touching_nodes[side_n][touching_node_n];
18659
                            //ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
18660
                            //draw_list->AddRect(touching_node->Pos, touching_node->Pos + touching_node->Size, IM_COL32(255, 128, 0, 255));
18661
0
                            while (touching_node->ParentNode != node)
18662
0
                            {
18663
0
                                if (touching_node->ParentNode->SplitAxis == axis)
18664
0
                                {
18665
                                    // Mark other node so its size will be preserved during the upcoming call to DockNodeTreeUpdatePosSize().
18666
0
                                    ImGuiDockNode* node_to_preserve = touching_node->ParentNode->ChildNodes[side_n];
18667
0
                                    node_to_preserve->WantLockSizeOnce = true;
18668
                                    //draw_list->AddRect(touching_node->Pos, touching_node->Rect().Max, IM_COL32(255, 0, 0, 255));
18669
                                    //draw_list->AddRectFilled(node_to_preserve->Pos, node_to_preserve->Rect().Max, IM_COL32(0, 255, 0, 100));
18670
0
                                }
18671
0
                                touching_node = touching_node->ParentNode;
18672
0
                            }
18673
0
                        }
18674
18675
0
                    DockNodeTreeUpdatePosSize(child_0, child_0->Pos, child_0->Size);
18676
0
                    DockNodeTreeUpdatePosSize(child_1, child_1->Pos, child_1->Size);
18677
0
                    MarkIniSettingsDirty();
18678
0
                }
18679
0
            }
18680
0
            PopID();
18681
0
        }
18682
0
    }
18683
18684
0
    if (child_0->IsVisible)
18685
0
        DockNodeTreeUpdateSplitter(child_0);
18686
0
    if (child_1->IsVisible)
18687
0
        DockNodeTreeUpdateSplitter(child_1);
18688
0
}
18689
18690
ImGuiDockNode* ImGui::DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node)
18691
0
{
18692
0
    if (node->IsLeafNode())
18693
0
        return node;
18694
0
    if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[0]))
18695
0
        return leaf_node;
18696
0
    if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[1]))
18697
0
        return leaf_node;
18698
0
    return NULL;
18699
0
}
18700
18701
ImGuiDockNode* ImGui::DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos)
18702
0
{
18703
0
    if (!node->IsVisible)
18704
0
        return NULL;
18705
18706
0
    const float dock_spacing = 0.0f;// g.Style.ItemInnerSpacing.x; // FIXME: Relation to DOCKING_SPLITTER_SIZE?
18707
0
    ImRect r(node->Pos, node->Pos + node->Size);
18708
0
    r.Expand(dock_spacing * 0.5f);
18709
0
    bool inside = r.Contains(pos);
18710
0
    if (!inside)
18711
0
        return NULL;
18712
18713
0
    if (node->IsLeafNode())
18714
0
        return node;
18715
0
    if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[0], pos))
18716
0
        return hovered_node;
18717
0
    if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[1], pos))
18718
0
        return hovered_node;
18719
18720
    // This means we are hovering over the splitter/spacing of a parent node
18721
0
    return node;
18722
0
}
18723
18724
//-----------------------------------------------------------------------------
18725
// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
18726
//-----------------------------------------------------------------------------
18727
// - SetWindowDock() [Internal]
18728
// - DockSpace()
18729
// - DockSpaceOverViewport()
18730
//-----------------------------------------------------------------------------
18731
18732
// [Internal] Called via SetNextWindowDockID()
18733
void ImGui::SetWindowDock(ImGuiWindow* window, ImGuiID dock_id, ImGuiCond cond)
18734
0
{
18735
    // Test condition (NB: bit 0 is always true) and clear flags for next time
18736
0
    if (cond && (window->SetWindowDockAllowFlags & cond) == 0)
18737
0
        return;
18738
0
    window->SetWindowDockAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
18739
18740
0
    if (window->DockId == dock_id)
18741
0
        return;
18742
18743
    // If the user attempt to set a dock id that is a split node, we'll dig within to find a suitable docking spot
18744
0
    ImGuiContext& g = *GImGui;
18745
0
    if (ImGuiDockNode* new_node = DockContextFindNodeByID(&g, dock_id))
18746
0
        if (new_node->IsSplitNode())
18747
0
        {
18748
            // Policy: Find central node or latest focused node. We first move back to our root node.
18749
0
            new_node = DockNodeGetRootNode(new_node);
18750
0
            if (new_node->CentralNode)
18751
0
            {
18752
0
                IM_ASSERT(new_node->CentralNode->IsCentralNode());
18753
0
                dock_id = new_node->CentralNode->ID;
18754
0
            }
18755
0
            else
18756
0
            {
18757
0
                dock_id = new_node->LastFocusedNodeId;
18758
0
            }
18759
0
        }
18760
18761
0
    if (window->DockId == dock_id)
18762
0
        return;
18763
18764
0
    if (window->DockNode)
18765
0
        DockNodeRemoveWindow(window->DockNode, window, 0);
18766
0
    window->DockId = dock_id;
18767
0
}
18768
18769
// Create an explicit dockspace node within an existing window. Also expose dock node flags and creates a CentralNode by default.
18770
// The Central Node is always displayed even when empty and shrink/extend according to the requested size of its neighbors.
18771
// DockSpace() needs to be submitted _before_ any window they can host. If you use a dockspace, submit it early in your app.
18772
// When ImGuiDockNodeFlags_KeepAliveOnly is set, nothing is submitted in the current window (function may be called from any location).
18773
ImGuiID ImGui::DockSpace(ImGuiID dockspace_id, const ImVec2& size_arg, ImGuiDockNodeFlags flags, const ImGuiWindowClass* window_class)
18774
0
{
18775
0
    ImGuiContext& g = *GImGui;
18776
0
    ImGuiWindow* window = GetCurrentWindowRead();
18777
0
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
18778
0
        return 0;
18779
18780
    // Early out if parent window is hidden/collapsed
18781
    // This is faster but also DockNodeUpdateTabBar() relies on TabBarLayout() running (which won't if SkipItems=true) to set NextSelectedTabId = 0). See #2960.
18782
    // If for whichever reason this is causing problem we would need to ensure that DockNodeUpdateTabBar() ends up clearing NextSelectedTabId even if SkipItems=true.
18783
0
    if (window->SkipItems)
18784
0
        flags |= ImGuiDockNodeFlags_KeepAliveOnly;
18785
0
    if ((flags & ImGuiDockNodeFlags_KeepAliveOnly) == 0)
18786
0
        window = GetCurrentWindow(); // call to set window->WriteAccessed = true;
18787
18788
0
    IM_ASSERT((flags & ImGuiDockNodeFlags_DockSpace) == 0);
18789
0
    IM_ASSERT(dockspace_id != 0);
18790
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, dockspace_id);
18791
0
    if (node == NULL)
18792
0
    {
18793
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X created\n", dockspace_id);
18794
0
        node = DockContextAddNode(&g, dockspace_id);
18795
0
        node->SetLocalFlags(ImGuiDockNodeFlags_CentralNode);
18796
0
    }
18797
0
    if (window_class && window_class->ClassId != node->WindowClass.ClassId)
18798
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X: setup WindowClass 0x%08X -> 0x%08X\n", dockspace_id, node->WindowClass.ClassId, window_class->ClassId);
18799
0
    node->SharedFlags = flags;
18800
0
    node->WindowClass = window_class ? *window_class : ImGuiWindowClass();
18801
18802
    // When a DockSpace transitioned form implicit to explicit this may be called a second time
18803
    // It is possible that the node has already been claimed by a docked window which appeared before the DockSpace() node, so we overwrite IsDockSpace again.
18804
0
    if (node->LastFrameActive == g.FrameCount && !(flags & ImGuiDockNodeFlags_KeepAliveOnly))
18805
0
    {
18806
0
        IM_ASSERT(node->IsDockSpace() == false && "Cannot call DockSpace() twice a frame with the same ID");
18807
0
        node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace);
18808
0
        return dockspace_id;
18809
0
    }
18810
0
    node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace);
18811
18812
    // Keep alive mode, this is allow windows docked into this node so stay docked even if they are not visible
18813
0
    if (flags & ImGuiDockNodeFlags_KeepAliveOnly)
18814
0
    {
18815
0
        node->LastFrameAlive = g.FrameCount;
18816
0
        return dockspace_id;
18817
0
    }
18818
18819
0
    const ImVec2 content_avail = GetContentRegionAvail();
18820
0
    ImVec2 size = ImTrunc(size_arg);
18821
0
    if (size.x <= 0.0f)
18822
0
        size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues)
18823
0
    if (size.y <= 0.0f)
18824
0
        size.y = ImMax(content_avail.y + size.y, 4.0f);
18825
0
    IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
18826
18827
0
    node->Pos = window->DC.CursorPos;
18828
0
    node->Size = node->SizeRef = size;
18829
0
    SetNextWindowPos(node->Pos);
18830
0
    SetNextWindowSize(node->Size);
18831
0
    g.NextWindowData.PosUndock = false;
18832
18833
    // FIXME-DOCK: Why do we need a child window to host a dockspace, could we host it in the existing window?
18834
    // FIXME-DOCK: What is the reason for not simply calling BeginChild()? (OK to have a reason but should be commented)
18835
0
    ImGuiWindowFlags window_flags = ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_DockNodeHost;
18836
0
    window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar;
18837
0
    window_flags |= ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse;
18838
0
    window_flags |= ImGuiWindowFlags_NoBackground;
18839
18840
0
    char title[256];
18841
0
    ImFormatString(title, IM_ARRAYSIZE(title), "%s/DockSpace_%08X", window->Name, dockspace_id);
18842
18843
0
    PushStyleVar(ImGuiStyleVar_ChildBorderSize, 0.0f);
18844
0
    Begin(title, NULL, window_flags);
18845
0
    PopStyleVar();
18846
18847
0
    ImGuiWindow* host_window = g.CurrentWindow;
18848
0
    DockNodeSetupHostWindow(node, host_window);
18849
0
    host_window->ChildId = window->GetID(title);
18850
0
    node->OnlyNodeWithWindows = NULL;
18851
18852
0
    IM_ASSERT(node->IsRootNode());
18853
18854
    // We need to handle the rare case were a central node is missing.
18855
    // This can happen if the node was first created manually with DockBuilderAddNode() but _without_ the ImGuiDockNodeFlags_Dockspace.
18856
    // Doing it correctly would set the _CentralNode flags, which would then propagate according to subsequent split.
18857
    // It would also be ambiguous to attempt to assign a central node while there are split nodes, so we wait until there's a single node remaining.
18858
    // The specific sub-property of _CentralNode we are interested in recovering here is the "Don't delete when empty" property,
18859
    // as it doesn't make sense for an empty dockspace to not have this property.
18860
0
    if (node->IsLeafNode() && !node->IsCentralNode())
18861
0
        node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
18862
18863
    // Update the node
18864
0
    DockNodeUpdate(node);
18865
18866
0
    End();
18867
18868
0
    ImRect bb(node->Pos, node->Pos + size);
18869
0
    ItemSize(size);
18870
0
    ItemAdd(bb, dockspace_id, NULL, ImGuiItemFlags_NoNav); // Not a nav point (could be, would need to draw the nav rect and replicate/refactor activation from BeginChild(), but seems like CTRL+Tab works better here?)
18871
0
    if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) && IsWindowChildOf(g.HoveredWindow, host_window, false, true)) // To fullfill IsItemHovered(), similar to EndChild()
18872
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
18873
18874
0
    return dockspace_id;
18875
0
}
18876
18877
// Tips: Use with ImGuiDockNodeFlags_PassthruCentralNode!
18878
// The limitation with this call is that your window won't have a local menu bar, but you can also use BeginMainMenuBar().
18879
// Even though we could pass window flags, it would also require the user to be able to call BeginMenuBar() somehow meaning we can't Begin/End in a single function.
18880
// If you really want a menu bar inside the same window as the one hosting the dockspace, you will need to copy this code somewhere and tweak it.
18881
ImGuiID ImGui::DockSpaceOverViewport(ImGuiID dockspace_id, const ImGuiViewport* viewport, ImGuiDockNodeFlags dockspace_flags, const ImGuiWindowClass* window_class)
18882
0
{
18883
0
    if (viewport == NULL)
18884
0
        viewport = GetMainViewport();
18885
18886
    // Submit a window filling the entire viewport
18887
0
    SetNextWindowPos(viewport->WorkPos);
18888
0
    SetNextWindowSize(viewport->WorkSize);
18889
0
    SetNextWindowViewport(viewport->ID);
18890
18891
0
    ImGuiWindowFlags host_window_flags = 0;
18892
0
    host_window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDocking;
18893
0
    host_window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
18894
0
    if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode)
18895
0
        host_window_flags |= ImGuiWindowFlags_NoBackground;
18896
18897
0
    char label[32];
18898
0
    ImFormatString(label, IM_ARRAYSIZE(label), "WindowOverViewport_%08X", viewport->ID);
18899
18900
0
    PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
18901
0
    PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
18902
0
    PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
18903
0
    Begin(label, NULL, host_window_flags);
18904
0
    PopStyleVar(3);
18905
18906
    // Submit the dockspace
18907
0
    if (dockspace_id == 0)
18908
0
        dockspace_id = GetID("DockSpace");
18909
0
    DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags, window_class);
18910
18911
0
    End();
18912
18913
0
    return dockspace_id;
18914
0
}
18915
18916
//-----------------------------------------------------------------------------
18917
// Docking: Builder Functions
18918
//-----------------------------------------------------------------------------
18919
// Very early end-user API to manipulate dock nodes.
18920
// Only available in imgui_internal.h. Expect this API to change/break!
18921
// It is expected that those functions are all called _before_ the dockspace node submission.
18922
//-----------------------------------------------------------------------------
18923
// - DockBuilderDockWindow()
18924
// - DockBuilderGetNode()
18925
// - DockBuilderSetNodePos()
18926
// - DockBuilderSetNodeSize()
18927
// - DockBuilderAddNode()
18928
// - DockBuilderRemoveNode()
18929
// - DockBuilderRemoveNodeChildNodes()
18930
// - DockBuilderRemoveNodeDockedWindows()
18931
// - DockBuilderSplitNode()
18932
// - DockBuilderCopyNodeRec()
18933
// - DockBuilderCopyNode()
18934
// - DockBuilderCopyWindowSettings()
18935
// - DockBuilderCopyDockSpace()
18936
// - DockBuilderFinish()
18937
//-----------------------------------------------------------------------------
18938
18939
void ImGui::DockBuilderDockWindow(const char* window_name, ImGuiID node_id)
18940
0
{
18941
    // We don't preserve relative order of multiple docked windows (by clearing DockOrder back to -1)
18942
0
    ImGuiContext& g = *GImGui; IM_UNUSED(g);
18943
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderDockWindow '%s' to node 0x%08X\n", window_name, node_id);
18944
0
    ImGuiID window_id = ImHashStr(window_name);
18945
0
    if (ImGuiWindow* window = FindWindowByID(window_id))
18946
0
    {
18947
        // Apply to created window
18948
0
        ImGuiID prev_node_id = window->DockId;
18949
0
        SetWindowDock(window, node_id, ImGuiCond_Always);
18950
0
        if (window->DockId != prev_node_id)
18951
0
            window->DockOrder = -1;
18952
0
    }
18953
0
    else
18954
0
    {
18955
        // Apply to settings
18956
0
        ImGuiWindowSettings* settings = FindWindowSettingsByID(window_id);
18957
0
        if (settings == NULL)
18958
0
            settings = CreateNewWindowSettings(window_name);
18959
0
        if (settings->DockId != node_id)
18960
0
            settings->DockOrder = -1;
18961
0
        settings->DockId = node_id;
18962
0
    }
18963
0
}
18964
18965
ImGuiDockNode* ImGui::DockBuilderGetNode(ImGuiID node_id)
18966
0
{
18967
0
    ImGuiContext& g = *GImGui;
18968
0
    return DockContextFindNodeByID(&g, node_id);
18969
0
}
18970
18971
void ImGui::DockBuilderSetNodePos(ImGuiID node_id, ImVec2 pos)
18972
0
{
18973
0
    ImGuiContext& g = *GImGui;
18974
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, node_id);
18975
0
    if (node == NULL)
18976
0
        return;
18977
0
    node->Pos = pos;
18978
0
    node->AuthorityForPos = ImGuiDataAuthority_DockNode;
18979
0
}
18980
18981
void ImGui::DockBuilderSetNodeSize(ImGuiID node_id, ImVec2 size)
18982
0
{
18983
0
    ImGuiContext& g = *GImGui;
18984
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, node_id);
18985
0
    if (node == NULL)
18986
0
        return;
18987
0
    IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
18988
0
    node->Size = node->SizeRef = size;
18989
0
    node->AuthorityForSize = ImGuiDataAuthority_DockNode;
18990
0
}
18991
18992
// Make sure to use the ImGuiDockNodeFlags_DockSpace flag to create a dockspace node! Otherwise this will create a floating node!
18993
// - Floating node: you can then call DockBuilderSetNodePos()/DockBuilderSetNodeSize() to position and size the floating node.
18994
// - Dockspace node: calling DockBuilderSetNodePos() is unnecessary.
18995
// - If you intend to split a node immediately after creation using DockBuilderSplitNode(), make sure to call DockBuilderSetNodeSize() beforehand!
18996
//   For various reason, the splitting code currently needs a base size otherwise space may not be allocated as precisely as you would expect.
18997
// - Use (id == 0) to let the system allocate a node identifier.
18998
// - Existing node with a same id will be removed.
18999
ImGuiID ImGui::DockBuilderAddNode(ImGuiID node_id, ImGuiDockNodeFlags flags)
19000
0
{
19001
0
    ImGuiContext& g = *GImGui; IM_UNUSED(g);
19002
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderAddNode 0x%08X flags=%08X\n", node_id, flags);
19003
19004
0
    if (node_id != 0)
19005
0
        DockBuilderRemoveNode(node_id);
19006
19007
0
    ImGuiDockNode* node = NULL;
19008
0
    if (flags & ImGuiDockNodeFlags_DockSpace)
19009
0
    {
19010
0
        DockSpace(node_id, ImVec2(0, 0), (flags & ~ImGuiDockNodeFlags_DockSpace) | ImGuiDockNodeFlags_KeepAliveOnly);
19011
0
        node = DockContextFindNodeByID(&g, node_id);
19012
0
    }
19013
0
    else
19014
0
    {
19015
0
        node = DockContextAddNode(&g, node_id);
19016
0
        node->SetLocalFlags(flags);
19017
0
    }
19018
0
    node->LastFrameAlive = g.FrameCount;   // Set this otherwise BeginDocked will undock during the same frame.
19019
0
    return node->ID;
19020
0
}
19021
19022
void ImGui::DockBuilderRemoveNode(ImGuiID node_id)
19023
0
{
19024
0
    ImGuiContext& g = *GImGui; IM_UNUSED(g);
19025
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderRemoveNode 0x%08X\n", node_id);
19026
19027
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, node_id);
19028
0
    if (node == NULL)
19029
0
        return;
19030
0
    DockBuilderRemoveNodeDockedWindows(node_id, true);
19031
0
    DockBuilderRemoveNodeChildNodes(node_id);
19032
    // Node may have moved or deleted if e.g. any merge happened
19033
0
    node = DockContextFindNodeByID(&g, node_id);
19034
0
    if (node == NULL)
19035
0
        return;
19036
0
    if (node->IsCentralNode() && node->ParentNode)
19037
0
        node->ParentNode->SetLocalFlags(node->ParentNode->LocalFlags | ImGuiDockNodeFlags_CentralNode);
19038
0
    DockContextRemoveNode(&g, node, true);
19039
0
}
19040
19041
// root_id = 0 to remove all, root_id != 0 to remove child of given node.
19042
void ImGui::DockBuilderRemoveNodeChildNodes(ImGuiID root_id)
19043
0
{
19044
0
    ImGuiContext& g = *GImGui;
19045
0
    ImGuiDockContext* dc = &g.DockContext;
19046
19047
0
    ImGuiDockNode* root_node = root_id ? DockContextFindNodeByID(&g, root_id) : NULL;
19048
0
    if (root_id && root_node == NULL)
19049
0
        return;
19050
0
    bool has_central_node = false;
19051
19052
0
    ImGuiDataAuthority backup_root_node_authority_for_pos = root_node ? root_node->AuthorityForPos : ImGuiDataAuthority_Auto;
19053
0
    ImGuiDataAuthority backup_root_node_authority_for_size = root_node ? root_node->AuthorityForSize : ImGuiDataAuthority_Auto;
19054
19055
    // Process active windows
19056
0
    ImVector<ImGuiDockNode*> nodes_to_remove;
19057
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
19058
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
19059
0
        {
19060
0
            bool want_removal = (root_id == 0) || (node->ID != root_id && DockNodeGetRootNode(node)->ID == root_id);
19061
0
            if (want_removal)
19062
0
            {
19063
0
                if (node->IsCentralNode())
19064
0
                    has_central_node = true;
19065
0
                if (root_id != 0)
19066
0
                    DockContextQueueNotifyRemovedNode(&g, node);
19067
0
                if (root_node)
19068
0
                {
19069
0
                    DockNodeMoveWindows(root_node, node);
19070
0
                    DockSettingsRenameNodeReferences(node->ID, root_node->ID);
19071
0
                }
19072
0
                nodes_to_remove.push_back(node);
19073
0
            }
19074
0
        }
19075
19076
    // DockNodeMoveWindows->DockNodeAddWindow will normally set those when reaching two windows (which is only adequate during interactive merge)
19077
    // Make sure we don't lose our current pos/size. (FIXME-DOCK: Consider tidying up that code in DockNodeAddWindow instead)
19078
0
    if (root_node)
19079
0
    {
19080
0
        root_node->AuthorityForPos = backup_root_node_authority_for_pos;
19081
0
        root_node->AuthorityForSize = backup_root_node_authority_for_size;
19082
0
    }
19083
19084
    // Apply to settings
19085
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19086
0
        if (ImGuiID window_settings_dock_id = settings->DockId)
19087
0
            for (int n = 0; n < nodes_to_remove.Size; n++)
19088
0
                if (nodes_to_remove[n]->ID == window_settings_dock_id)
19089
0
                {
19090
0
                    settings->DockId = root_id;
19091
0
                    break;
19092
0
                }
19093
19094
    // Not really efficient, but easier to destroy a whole hierarchy considering DockContextRemoveNode is attempting to merge nodes
19095
0
    if (nodes_to_remove.Size > 1)
19096
0
        ImQsort(nodes_to_remove.Data, nodes_to_remove.Size, sizeof(ImGuiDockNode*), DockNodeComparerDepthMostFirst);
19097
0
    for (int n = 0; n < nodes_to_remove.Size; n++)
19098
0
        DockContextRemoveNode(&g, nodes_to_remove[n], false);
19099
19100
0
    if (root_id == 0)
19101
0
    {
19102
0
        dc->Nodes.Clear();
19103
0
        dc->Requests.clear();
19104
0
    }
19105
0
    else if (has_central_node)
19106
0
    {
19107
0
        root_node->CentralNode = root_node;
19108
0
        root_node->SetLocalFlags(root_node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
19109
0
    }
19110
0
}
19111
19112
void ImGui::DockBuilderRemoveNodeDockedWindows(ImGuiID root_id, bool clear_settings_refs)
19113
0
{
19114
    // Clear references in settings
19115
0
    ImGuiContext& g = *GImGui;
19116
0
    if (clear_settings_refs)
19117
0
    {
19118
0
        for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19119
0
        {
19120
0
            bool want_removal = (root_id == 0) || (settings->DockId == root_id);
19121
0
            if (!want_removal && settings->DockId != 0)
19122
0
                if (ImGuiDockNode* node = DockContextFindNodeByID(&g, settings->DockId))
19123
0
                    if (DockNodeGetRootNode(node)->ID == root_id)
19124
0
                        want_removal = true;
19125
0
            if (want_removal)
19126
0
                settings->DockId = 0;
19127
0
        }
19128
0
    }
19129
19130
    // Clear references in windows
19131
0
    for (int n = 0; n < g.Windows.Size; n++)
19132
0
    {
19133
0
        ImGuiWindow* window = g.Windows[n];
19134
0
        bool want_removal = (root_id == 0) || (window->DockNode && DockNodeGetRootNode(window->DockNode)->ID == root_id) || (window->DockNodeAsHost && window->DockNodeAsHost->ID == root_id);
19135
0
        if (want_removal)
19136
0
        {
19137
0
            const ImGuiID backup_dock_id = window->DockId;
19138
0
            IM_UNUSED(backup_dock_id);
19139
0
            DockContextProcessUndockWindow(&g, window, clear_settings_refs);
19140
0
            if (!clear_settings_refs)
19141
0
                IM_ASSERT(window->DockId == backup_dock_id);
19142
0
        }
19143
0
    }
19144
0
}
19145
19146
// If 'out_id_at_dir' or 'out_id_at_opposite_dir' are non NULL, the function will write out the ID of the two new nodes created.
19147
// Return value is ID of the node at the specified direction, so same as (*out_id_at_dir) if that pointer is set.
19148
// FIXME-DOCK: We are not exposing nor using split_outer.
19149
ImGuiID ImGui::DockBuilderSplitNode(ImGuiID id, ImGuiDir split_dir, float size_ratio_for_node_at_dir, ImGuiID* out_id_at_dir, ImGuiID* out_id_at_opposite_dir)
19150
0
{
19151
0
    ImGuiContext& g = *GImGui;
19152
0
    IM_ASSERT(split_dir != ImGuiDir_None);
19153
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderSplitNode: node 0x%08X, split_dir %d\n", id, split_dir);
19154
19155
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, id);
19156
0
    if (node == NULL)
19157
0
    {
19158
0
        IM_ASSERT(node != NULL);
19159
0
        return 0;
19160
0
    }
19161
19162
0
    IM_ASSERT(!node->IsSplitNode()); // Assert if already Split
19163
19164
0
    ImGuiDockRequest req;
19165
0
    req.Type = ImGuiDockRequestType_Split;
19166
0
    req.DockTargetWindow = NULL;
19167
0
    req.DockTargetNode = node;
19168
0
    req.DockPayload = NULL;
19169
0
    req.DockSplitDir = split_dir;
19170
0
    req.DockSplitRatio = ImSaturate((split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? size_ratio_for_node_at_dir : 1.0f - size_ratio_for_node_at_dir);
19171
0
    req.DockSplitOuter = false;
19172
0
    DockContextProcessDock(&g, &req);
19173
19174
0
    ImGuiID id_at_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 0 : 1]->ID;
19175
0
    ImGuiID id_at_opposite_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0]->ID;
19176
0
    if (out_id_at_dir)
19177
0
        *out_id_at_dir = id_at_dir;
19178
0
    if (out_id_at_opposite_dir)
19179
0
        *out_id_at_opposite_dir = id_at_opposite_dir;
19180
0
    return id_at_dir;
19181
0
}
19182
19183
static ImGuiDockNode* DockBuilderCopyNodeRec(ImGuiDockNode* src_node, ImGuiID dst_node_id_if_known, ImVector<ImGuiID>* out_node_remap_pairs)
19184
0
{
19185
0
    ImGuiContext& g = *GImGui;
19186
0
    ImGuiDockNode* dst_node = ImGui::DockContextAddNode(&g, dst_node_id_if_known);
19187
0
    dst_node->SharedFlags = src_node->SharedFlags;
19188
0
    dst_node->LocalFlags = src_node->LocalFlags;
19189
0
    dst_node->LocalFlagsInWindows = ImGuiDockNodeFlags_None;
19190
0
    dst_node->Pos = src_node->Pos;
19191
0
    dst_node->Size = src_node->Size;
19192
0
    dst_node->SizeRef = src_node->SizeRef;
19193
0
    dst_node->SplitAxis = src_node->SplitAxis;
19194
0
    dst_node->UpdateMergedFlags();
19195
19196
0
    out_node_remap_pairs->push_back(src_node->ID);
19197
0
    out_node_remap_pairs->push_back(dst_node->ID);
19198
19199
0
    for (int child_n = 0; child_n < IM_ARRAYSIZE(src_node->ChildNodes); child_n++)
19200
0
        if (src_node->ChildNodes[child_n])
19201
0
        {
19202
0
            dst_node->ChildNodes[child_n] = DockBuilderCopyNodeRec(src_node->ChildNodes[child_n], 0, out_node_remap_pairs);
19203
0
            dst_node->ChildNodes[child_n]->ParentNode = dst_node;
19204
0
        }
19205
19206
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] Fork node %08X -> %08X (%d childs)\n", src_node->ID, dst_node->ID, dst_node->IsSplitNode() ? 2 : 0);
19207
0
    return dst_node;
19208
0
}
19209
19210
void ImGui::DockBuilderCopyNode(ImGuiID src_node_id, ImGuiID dst_node_id, ImVector<ImGuiID>* out_node_remap_pairs)
19211
0
{
19212
0
    ImGuiContext& g = *GImGui;
19213
0
    IM_ASSERT(src_node_id != 0);
19214
0
    IM_ASSERT(dst_node_id != 0);
19215
0
    IM_ASSERT(out_node_remap_pairs != NULL);
19216
19217
0
    DockBuilderRemoveNode(dst_node_id);
19218
19219
0
    ImGuiDockNode* src_node = DockContextFindNodeByID(&g, src_node_id);
19220
0
    IM_ASSERT(src_node != NULL);
19221
19222
0
    out_node_remap_pairs->clear();
19223
0
    DockBuilderCopyNodeRec(src_node, dst_node_id, out_node_remap_pairs);
19224
19225
0
    IM_ASSERT((out_node_remap_pairs->Size % 2) == 0);
19226
0
}
19227
19228
void ImGui::DockBuilderCopyWindowSettings(const char* src_name, const char* dst_name)
19229
0
{
19230
0
    ImGuiWindow* src_window = FindWindowByName(src_name);
19231
0
    if (src_window == NULL)
19232
0
        return;
19233
0
    if (ImGuiWindow* dst_window = FindWindowByName(dst_name))
19234
0
    {
19235
0
        dst_window->Pos = src_window->Pos;
19236
0
        dst_window->Size = src_window->Size;
19237
0
        dst_window->SizeFull = src_window->SizeFull;
19238
0
        dst_window->Collapsed = src_window->Collapsed;
19239
0
    }
19240
0
    else
19241
0
    {
19242
0
        ImGuiWindowSettings* dst_settings = FindWindowSettingsByID(ImHashStr(dst_name));
19243
0
        if (!dst_settings)
19244
0
            dst_settings = CreateNewWindowSettings(dst_name);
19245
0
        ImVec2ih window_pos_2ih = ImVec2ih(src_window->Pos);
19246
0
        if (src_window->ViewportId != 0 && src_window->ViewportId != IMGUI_VIEWPORT_DEFAULT_ID)
19247
0
        {
19248
0
            dst_settings->ViewportPos = window_pos_2ih;
19249
0
            dst_settings->ViewportId = src_window->ViewportId;
19250
0
            dst_settings->Pos = ImVec2ih(0, 0);
19251
0
        }
19252
0
        else
19253
0
        {
19254
0
            dst_settings->Pos = window_pos_2ih;
19255
0
        }
19256
0
        dst_settings->Size = ImVec2ih(src_window->SizeFull);
19257
0
        dst_settings->Collapsed = src_window->Collapsed;
19258
0
    }
19259
0
}
19260
19261
// FIXME: Will probably want to change this signature, in particular how the window remapping pairs are passed.
19262
void ImGui::DockBuilderCopyDockSpace(ImGuiID src_dockspace_id, ImGuiID dst_dockspace_id, ImVector<const char*>* in_window_remap_pairs)
19263
0
{
19264
0
    ImGuiContext& g = *GImGui;
19265
0
    IM_ASSERT(src_dockspace_id != 0);
19266
0
    IM_ASSERT(dst_dockspace_id != 0);
19267
0
    IM_ASSERT(in_window_remap_pairs != NULL);
19268
0
    IM_ASSERT((in_window_remap_pairs->Size % 2) == 0);
19269
19270
    // Duplicate entire dock
19271
    // FIXME: When overwriting dst_dockspace_id, windows that aren't part of our dockspace window class but that are docked in a same node will be split apart,
19272
    // whereas we could attempt to at least keep them together in a new, same floating node.
19273
0
    ImVector<ImGuiID> node_remap_pairs;
19274
0
    DockBuilderCopyNode(src_dockspace_id, dst_dockspace_id, &node_remap_pairs);
19275
19276
    // Attempt to transition all the upcoming windows associated to dst_dockspace_id into the newly created hierarchy of dock nodes
19277
    // (The windows associated to src_dockspace_id are staying in place)
19278
0
    ImVector<ImGuiID> src_windows;
19279
0
    for (int remap_window_n = 0; remap_window_n < in_window_remap_pairs->Size; remap_window_n += 2)
19280
0
    {
19281
0
        const char* src_window_name = (*in_window_remap_pairs)[remap_window_n];
19282
0
        const char* dst_window_name = (*in_window_remap_pairs)[remap_window_n + 1];
19283
0
        ImGuiID src_window_id = ImHashStr(src_window_name);
19284
0
        src_windows.push_back(src_window_id);
19285
19286
        // Search in the remapping tables
19287
0
        ImGuiID src_dock_id = 0;
19288
0
        if (ImGuiWindow* src_window = FindWindowByID(src_window_id))
19289
0
            src_dock_id = src_window->DockId;
19290
0
        else if (ImGuiWindowSettings* src_window_settings = FindWindowSettingsByID(src_window_id))
19291
0
            src_dock_id = src_window_settings->DockId;
19292
0
        ImGuiID dst_dock_id = 0;
19293
0
        for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
19294
0
            if (node_remap_pairs[dock_remap_n] == src_dock_id)
19295
0
            {
19296
0
                dst_dock_id = node_remap_pairs[dock_remap_n + 1];
19297
                //node_remap_pairs[dock_remap_n] = node_remap_pairs[dock_remap_n + 1] = 0; // Clear
19298
0
                break;
19299
0
            }
19300
19301
0
        if (dst_dock_id != 0)
19302
0
        {
19303
            // Docked windows gets redocked into the new node hierarchy.
19304
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] Remap live window '%s' 0x%08X -> '%s' 0x%08X\n", src_window_name, src_dock_id, dst_window_name, dst_dock_id);
19305
0
            DockBuilderDockWindow(dst_window_name, dst_dock_id);
19306
0
        }
19307
0
        else
19308
0
        {
19309
            // Floating windows gets their settings transferred (regardless of whether the new window already exist or not)
19310
            // When this is leading to a Copy and not a Move, we would get two overlapping floating windows. Could we possibly dock them together?
19311
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window settings '%s' -> '%s'\n", src_window_name, dst_window_name);
19312
0
            DockBuilderCopyWindowSettings(src_window_name, dst_window_name);
19313
0
        }
19314
0
    }
19315
19316
    // Anything else in the source nodes of 'node_remap_pairs' are windows that are not included in the remapping list.
19317
    // Find those windows and move to them to the cloned dock node. This may be optional?
19318
    // Dock those are a second step as undocking would invalidate source dock nodes.
19319
0
    struct DockRemainingWindowTask { ImGuiWindow* Window; ImGuiID DockId; DockRemainingWindowTask(ImGuiWindow* window, ImGuiID dock_id) { Window = window; DockId = dock_id; } };
19320
0
    ImVector<DockRemainingWindowTask> dock_remaining_windows;
19321
0
    for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
19322
0
        if (ImGuiID src_dock_id = node_remap_pairs[dock_remap_n])
19323
0
        {
19324
0
            ImGuiID dst_dock_id = node_remap_pairs[dock_remap_n + 1];
19325
0
            ImGuiDockNode* node = DockBuilderGetNode(src_dock_id);
19326
0
            for (int window_n = 0; window_n < node->Windows.Size; window_n++)
19327
0
            {
19328
0
                ImGuiWindow* window = node->Windows[window_n];
19329
0
                if (src_windows.contains(window->ID))
19330
0
                    continue;
19331
19332
                // Docked windows gets redocked into the new node hierarchy.
19333
0
                IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window '%s' %08X -> %08X\n", window->Name, src_dock_id, dst_dock_id);
19334
0
                dock_remaining_windows.push_back(DockRemainingWindowTask(window, dst_dock_id));
19335
0
            }
19336
0
        }
19337
0
    for (const DockRemainingWindowTask& task : dock_remaining_windows)
19338
0
        DockBuilderDockWindow(task.Window->Name, task.DockId);
19339
0
}
19340
19341
// FIXME-DOCK: This is awkward because in series of split user is likely to loose access to its root node.
19342
void ImGui::DockBuilderFinish(ImGuiID root_id)
19343
0
{
19344
0
    ImGuiContext& g = *GImGui;
19345
    //DockContextRebuild(&g);
19346
0
    DockContextBuildAddWindowsToNodes(&g, root_id);
19347
0
}
19348
19349
//-----------------------------------------------------------------------------
19350
// Docking: Begin/End Support Functions (called from Begin/End)
19351
//-----------------------------------------------------------------------------
19352
// - GetWindowAlwaysWantOwnTabBar()
19353
// - DockContextBindNodeToWindow()
19354
// - BeginDocked()
19355
// - BeginDockableDragDropSource()
19356
// - BeginDockableDragDropTarget()
19357
//-----------------------------------------------------------------------------
19358
19359
bool ImGui::GetWindowAlwaysWantOwnTabBar(ImGuiWindow* window)
19360
193k
{
19361
193k
    ImGuiContext& g = *GImGui;
19362
193k
    if (g.IO.ConfigDockingAlwaysTabBar || window->WindowClass.DockingAlwaysTabBar)
19363
0
        if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking)) == 0)
19364
0
            if (!window->IsFallbackWindow)    // We don't support AlwaysTabBar on the fallback/implicit window to avoid unused dock-node overhead/noise
19365
0
                return true;
19366
193k
    return false;
19367
193k
}
19368
19369
static ImGuiDockNode* ImGui::DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window)
19370
0
{
19371
0
    ImGuiContext& g = *ctx;
19372
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
19373
0
    IM_ASSERT(window->DockNode == NULL);
19374
19375
    // We should not be docking into a split node (SetWindowDock should avoid this)
19376
0
    if (node && node->IsSplitNode())
19377
0
    {
19378
0
        DockContextProcessUndockWindow(ctx, window);
19379
0
        return NULL;
19380
0
    }
19381
19382
    // Create node
19383
0
    if (node == NULL)
19384
0
    {
19385
0
        node = DockContextAddNode(ctx, window->DockId);
19386
0
        node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
19387
0
        node->LastFrameAlive = g.FrameCount;
19388
0
    }
19389
19390
    // If the node just turned visible and is part of a hierarchy, it doesn't have a Size assigned by DockNodeTreeUpdatePosSize() yet,
19391
    // so we're forcing a Pos/Size update from the first ancestor that is already visible (often it will be the root node).
19392
    // If we don't do this, the window will be assigned a zero-size on its first frame, which won't ideally warm up the layout.
19393
    // This is a little wonky because we don't normally update the Pos/Size of visible node mid-frame.
19394
0
    if (!node->IsVisible)
19395
0
    {
19396
0
        ImGuiDockNode* ancestor_node = node;
19397
0
        while (!ancestor_node->IsVisible && ancestor_node->ParentNode)
19398
0
            ancestor_node = ancestor_node->ParentNode;
19399
0
        IM_ASSERT(ancestor_node->Size.x > 0.0f && ancestor_node->Size.y > 0.0f);
19400
0
        DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(ancestor_node));
19401
0
        DockNodeTreeUpdatePosSize(ancestor_node, ancestor_node->Pos, ancestor_node->Size, node);
19402
0
    }
19403
19404
    // Add window to node
19405
0
    bool node_was_visible = node->IsVisible;
19406
0
    DockNodeAddWindow(node, window, true);
19407
0
    node->IsVisible = node_was_visible; // Don't mark visible right away (so DockContextEndFrame() doesn't render it, maybe other side effects? will see)
19408
0
    IM_ASSERT(node == window->DockNode);
19409
0
    return node;
19410
0
}
19411
19412
static void StoreDockStyleForWindow(ImGuiWindow* window)
19413
0
{
19414
0
    ImGuiContext& g = *GImGui;
19415
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
19416
0
        window->DockStyle.Colors[color_n] = ImGui::ColorConvertFloat4ToU32(g.Style.Colors[GWindowDockStyleColors[color_n]]);
19417
0
}
19418
19419
void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open)
19420
0
{
19421
0
    ImGuiContext& g = *GImGui;
19422
19423
    // Clear fields ahead so most early-out paths don't have to do it
19424
0
    window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
19425
19426
0
    const bool auto_dock_node = GetWindowAlwaysWantOwnTabBar(window);
19427
0
    if (auto_dock_node)
19428
0
    {
19429
0
        if (window->DockId == 0)
19430
0
        {
19431
0
            IM_ASSERT(window->DockNode == NULL);
19432
0
            window->DockId = DockContextGenNodeID(&g);
19433
0
        }
19434
0
    }
19435
0
    else
19436
0
    {
19437
        // Calling SetNextWindowPos() undock windows by default (by setting PosUndock)
19438
0
        bool want_undock = false;
19439
0
        want_undock |= (window->Flags & ImGuiWindowFlags_NoDocking) != 0;
19440
0
        want_undock |= (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) && (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) && g.NextWindowData.PosUndock;
19441
0
        if (want_undock)
19442
0
        {
19443
0
            DockContextProcessUndockWindow(&g, window);
19444
0
            return;
19445
0
        }
19446
0
    }
19447
19448
    // Bind to our dock node
19449
0
    ImGuiDockNode* node = window->DockNode;
19450
0
    if (node != NULL)
19451
0
        IM_ASSERT(window->DockId == node->ID);
19452
0
    if (window->DockId != 0 && node == NULL)
19453
0
    {
19454
0
        node = DockContextBindNodeToWindow(&g, window);
19455
0
        if (node == NULL)
19456
0
            return;
19457
0
    }
19458
19459
#if 0
19460
    // Undock if the ImGuiDockNodeFlags_NoDockingInCentralNode got set
19461
    if (node->IsCentralNode && (node->Flags & ImGuiDockNodeFlags_NoDockingInCentralNode))
19462
    {
19463
        DockContextProcessUndockWindow(ctx, window);
19464
        return;
19465
    }
19466
#endif
19467
19468
    // Undock if our dockspace node disappeared
19469
    // Note how we are testing for LastFrameAlive and NOT LastFrameActive. A DockSpace node can be maintained alive while being inactive with ImGuiDockNodeFlags_KeepAliveOnly.
19470
0
    if (node->LastFrameAlive < g.FrameCount)
19471
0
    {
19472
        // If the window has been orphaned, transition the docknode to an implicit node processed in DockContextNewFrameUpdateDocking()
19473
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
19474
0
        if (root_node->LastFrameAlive < g.FrameCount)
19475
0
            DockContextProcessUndockWindow(&g, window);
19476
0
        else
19477
0
            window->DockIsActive = true;
19478
0
        return;
19479
0
    }
19480
19481
    // Store style overrides
19482
0
    StoreDockStyleForWindow(window);
19483
19484
    // Fast path return. It is common for windows to hold on a persistent DockId but be the only visible window,
19485
    // and never create neither a host window neither a tab bar.
19486
    // FIXME-DOCK: replace ->HostWindow NULL compare with something more explicit (~was initially intended as a first frame test)
19487
0
    if (node->HostWindow == NULL)
19488
0
    {
19489
0
        if (node->State == ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing)
19490
0
            window->DockIsActive = true;
19491
0
        if (node->Windows.Size > 1 && window->Appearing) // Only hide appearing window
19492
0
            DockNodeHideWindowDuringHostWindowCreation(window);
19493
0
        return;
19494
0
    }
19495
19496
    // We can have zero-sized nodes (e.g. children of a small-size dockspace)
19497
0
    IM_ASSERT(node->HostWindow);
19498
0
    IM_ASSERT(node->IsLeafNode());
19499
0
    IM_ASSERT(node->Size.x >= 0.0f && node->Size.y >= 0.0f);
19500
0
    node->State = ImGuiDockNodeState_HostWindowVisible;
19501
19502
    // Undock if we are submitted earlier than the host window
19503
0
    if (!(node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly) && window->BeginOrderWithinContext < node->HostWindow->BeginOrderWithinContext)
19504
0
    {
19505
0
        DockContextProcessUndockWindow(&g, window);
19506
0
        return;
19507
0
    }
19508
19509
    // Position/Size window
19510
0
    SetNextWindowPos(node->Pos);
19511
0
    SetNextWindowSize(node->Size);
19512
0
    g.NextWindowData.PosUndock = false; // Cancel implicit undocking of SetNextWindowPos()
19513
0
    window->DockIsActive = true;
19514
0
    window->DockNodeIsVisible = true;
19515
0
    window->DockTabIsVisible = false;
19516
0
    if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
19517
0
        return;
19518
19519
    // When the window is selected we mark it as visible.
19520
0
    if (node->VisibleWindow == window)
19521
0
        window->DockTabIsVisible = true;
19522
19523
    // Update window flag
19524
0
    IM_ASSERT((window->Flags & ImGuiWindowFlags_ChildWindow) == 0);
19525
0
    window->Flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoResize;
19526
0
    window->ChildFlags |= ImGuiChildFlags_AlwaysUseWindowPadding;
19527
0
    if (node->IsHiddenTabBar() || node->IsNoTabBar())
19528
0
        window->Flags |= ImGuiWindowFlags_NoTitleBar;
19529
0
    else
19530
0
        window->Flags &= ~ImGuiWindowFlags_NoTitleBar;      // Clear the NoTitleBar flag in case the user set it: confusingly enough we need a title bar height so we are correctly offset, but it won't be displayed!
19531
19532
    // Save new dock order only if the window has been visible once already
19533
    // This allows multiple windows to be created in the same frame and have their respective dock orders preserved.
19534
0
    if (node->TabBar && window->WasActive)
19535
0
        window->DockOrder = (short)DockNodeGetTabOrder(window);
19536
19537
0
    if ((node->WantCloseAll || node->WantCloseTabId == window->TabId) && p_open != NULL)
19538
0
        *p_open = false;
19539
19540
    // Update ChildId to allow returning from Child to Parent with Escape
19541
0
    ImGuiWindow* parent_window = window->DockNode->HostWindow;
19542
0
    window->ChildId = parent_window->GetID(window->Name);
19543
0
}
19544
19545
void ImGui::BeginDockableDragDropSource(ImGuiWindow* window)
19546
0
{
19547
0
    ImGuiContext& g = *GImGui;
19548
0
    IM_ASSERT(g.ActiveId == window->MoveId);
19549
0
    IM_ASSERT(g.MovingWindow == window);
19550
0
    IM_ASSERT(g.CurrentWindow == window);
19551
19552
    // 0: Hold SHIFT to disable docking, 1: Hold SHIFT to enable docking.
19553
0
    if (g.IO.ConfigDockingWithShift != g.IO.KeyShift)
19554
0
    {
19555
        // When ConfigDockingWithShift is set, display a tooltip to increase UI affordance.
19556
        // We cannot set for HoveredWindowUnderMovingWindow != NULL here, as it is only valid/useful when drag and drop is already active
19557
        // (because of the 'is_mouse_dragging_with_an_expected_destination' logic in UpdateViewportsNewFrame() function)
19558
0
        IM_ASSERT(g.NextWindowData.Flags == 0);
19559
0
        if (g.IO.ConfigDockingWithShift && g.MouseStationaryTimer >= 1.0f && g.ActiveId >= 1.0f)
19560
0
            SetTooltip("%s", LocalizeGetMsg(ImGuiLocKey_DockingHoldShiftToDock));
19561
0
        return;
19562
0
    }
19563
19564
0
    g.LastItemData.ID = window->MoveId;
19565
0
    window = window->RootWindowDockTree;
19566
0
    IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
19567
0
    bool is_drag_docking = (g.IO.ConfigDockingWithShift) || ImRect(0, 0, window->SizeFull.x, GetFrameHeight()).Contains(g.ActiveIdClickOffset); // FIXME-DOCKING: Need to make this stateful and explicit
19568
0
    ImGuiDragDropFlags drag_drop_flags = ImGuiDragDropFlags_SourceNoPreviewTooltip | ImGuiDragDropFlags_SourceNoHoldToOpenOthers | ImGuiDragDropFlags_PayloadAutoExpire | ImGuiDragDropFlags_PayloadNoCrossContext | ImGuiDragDropFlags_PayloadNoCrossProcess;
19569
0
    if (is_drag_docking && BeginDragDropSource(drag_drop_flags))
19570
0
    {
19571
0
        SetDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, &window, sizeof(window));
19572
0
        EndDragDropSource();
19573
0
        StoreDockStyleForWindow(window); // Store style overrides while dragging (even when not docked) because docking preview may need it.
19574
0
    }
19575
0
}
19576
19577
void ImGui::BeginDockableDragDropTarget(ImGuiWindow* window)
19578
0
{
19579
0
    ImGuiContext& g = *GImGui;
19580
19581
    //IM_ASSERT(window->RootWindowDockTree == window); // May also be a DockSpace
19582
0
    IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
19583
0
    if (!g.DragDropActive)
19584
0
        return;
19585
    //GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
19586
0
    if (!BeginDragDropTargetCustom(window->Rect(), window->ID))
19587
0
        return;
19588
19589
    // Peek into the payload before calling AcceptDragDropPayload() so we can handle overlapping dock nodes with filtering
19590
    // (this is a little unusual pattern, normally most code would call AcceptDragDropPayload directly)
19591
0
    const ImGuiPayload* payload = &g.DragDropPayload;
19592
0
    if (!payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) || !DockNodeIsDropAllowed(window, *(ImGuiWindow**)payload->Data))
19593
0
    {
19594
0
        EndDragDropTarget();
19595
0
        return;
19596
0
    }
19597
19598
0
    ImGuiWindow* payload_window = *(ImGuiWindow**)payload->Data;
19599
0
    if (AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect))
19600
0
    {
19601
        // Select target node
19602
        // (Important: we cannot use g.HoveredDockNode here! Because each of our target node have filters based on payload, each candidate drop target will do its own evaluation)
19603
0
        bool dock_into_floating_window = false;
19604
0
        ImGuiDockNode* node = NULL;
19605
0
        if (window->DockNodeAsHost)
19606
0
        {
19607
            // Cannot assume that node will != NULL even though we passed the rectangle test: it depends on padding/spacing handled by DockNodeTreeFindVisibleNodeByPos().
19608
0
            node = DockNodeTreeFindVisibleNodeByPos(window->DockNodeAsHost, g.IO.MousePos);
19609
19610
            // There is an edge case when docking into a dockspace which only has _inactive_ nodes (because none of the windows are active)
19611
            // In this case we need to fallback into any leaf mode, possibly the central node.
19612
            // FIXME-20181220: We should not have to test for IsLeafNode() here but we have another bug to fix first.
19613
0
            if (node && node->IsDockSpace() && node->IsRootNode())
19614
0
                node = (node->CentralNode && node->IsLeafNode()) ? node->CentralNode : DockNodeTreeFindFallbackLeafNode(node);
19615
0
        }
19616
0
        else
19617
0
        {
19618
0
            if (window->DockNode)
19619
0
                node = window->DockNode;
19620
0
            else
19621
0
                dock_into_floating_window = true; // Dock into a regular window
19622
0
        }
19623
19624
0
        const ImRect explicit_target_rect = (node && node->TabBar && !node->IsHiddenTabBar() && !node->IsNoTabBar()) ? node->TabBar->BarRect : ImRect(window->Pos, window->Pos + ImVec2(window->Size.x, GetFrameHeight()));
19625
0
        const bool is_explicit_target = g.IO.ConfigDockingWithShift || IsMouseHoveringRect(explicit_target_rect.Min, explicit_target_rect.Max);
19626
19627
        // Preview docking request and find out split direction/ratio
19628
        //const bool do_preview = true;     // Ignore testing for payload->IsPreview() which removes one frame of delay, but breaks overlapping drop targets within the same window.
19629
0
        const bool do_preview = payload->IsPreview() || payload->IsDelivery();
19630
0
        if (do_preview && (node != NULL || dock_into_floating_window))
19631
0
        {
19632
            // If we have a non-leaf node it means we are hovering the border of a parent node, in which case only outer markers will appear.
19633
0
            ImGuiDockPreviewData split_inner;
19634
0
            ImGuiDockPreviewData split_outer;
19635
0
            ImGuiDockPreviewData* split_data = &split_inner;
19636
0
            if (node && (node->ParentNode || node->IsCentralNode() || !node->IsLeafNode()))
19637
0
                if (ImGuiDockNode* root_node = DockNodeGetRootNode(node))
19638
0
                {
19639
0
                    DockNodePreviewDockSetup(window, root_node, payload_window, NULL, &split_outer, is_explicit_target, true);
19640
0
                    if (split_outer.IsSplitDirExplicit)
19641
0
                        split_data = &split_outer;
19642
0
                }
19643
0
            if (!node || node->IsLeafNode())
19644
0
                DockNodePreviewDockSetup(window, node, payload_window, NULL, &split_inner, is_explicit_target, false);
19645
0
            if (split_data == &split_outer)
19646
0
                split_inner.IsDropAllowed = false;
19647
19648
            // Draw inner then outer, so that previewed tab (in inner data) will be behind the outer drop boxes
19649
0
            DockNodePreviewDockRender(window, node, payload_window, &split_inner);
19650
0
            DockNodePreviewDockRender(window, node, payload_window, &split_outer);
19651
19652
            // Queue docking request
19653
0
            if (split_data->IsDropAllowed && payload->IsDelivery())
19654
0
                DockContextQueueDock(&g, window, split_data->SplitNode, payload_window, split_data->SplitDir, split_data->SplitRatio, split_data == &split_outer);
19655
0
        }
19656
0
    }
19657
0
    EndDragDropTarget();
19658
0
}
19659
19660
//-----------------------------------------------------------------------------
19661
// Docking: Settings
19662
//-----------------------------------------------------------------------------
19663
// - DockSettingsRenameNodeReferences()
19664
// - DockSettingsRemoveNodeReferences()
19665
// - DockSettingsFindNodeSettings()
19666
// - DockSettingsHandler_ApplyAll()
19667
// - DockSettingsHandler_ReadOpen()
19668
// - DockSettingsHandler_ReadLine()
19669
// - DockSettingsHandler_DockNodeToSettings()
19670
// - DockSettingsHandler_WriteAll()
19671
//-----------------------------------------------------------------------------
19672
19673
static void ImGui::DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id)
19674
0
{
19675
0
    ImGuiContext& g = *GImGui;
19676
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockSettingsRenameNodeReferences: from 0x%08X -> to 0x%08X\n", old_node_id, new_node_id);
19677
0
    for (int window_n = 0; window_n < g.Windows.Size; window_n++)
19678
0
    {
19679
0
        ImGuiWindow* window = g.Windows[window_n];
19680
0
        if (window->DockId == old_node_id && window->DockNode == NULL)
19681
0
            window->DockId = new_node_id;
19682
0
    }
19683
    //// FIXME-OPT: We could remove this loop by storing the index in the map
19684
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19685
0
        if (settings->DockId == old_node_id)
19686
0
            settings->DockId = new_node_id;
19687
0
}
19688
19689
// Remove references stored in ImGuiWindowSettings to the given ImGuiDockNodeSettings
19690
static void ImGui::DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count)
19691
0
{
19692
0
    ImGuiContext& g = *GImGui;
19693
0
    int found = 0;
19694
    //// FIXME-OPT: We could remove this loop by storing the index in the map
19695
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19696
0
        for (int node_n = 0; node_n < node_ids_count; node_n++)
19697
0
            if (settings->DockId == node_ids[node_n])
19698
0
            {
19699
0
                settings->DockId = 0;
19700
0
                settings->DockOrder = -1;
19701
0
                if (++found < node_ids_count)
19702
0
                    break;
19703
0
                return;
19704
0
            }
19705
0
}
19706
19707
static ImGuiDockNodeSettings* ImGui::DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID id)
19708
0
{
19709
    // FIXME-OPT
19710
0
    ImGuiDockContext* dc = &ctx->DockContext;
19711
0
    for (int n = 0; n < dc->NodesSettings.Size; n++)
19712
0
        if (dc->NodesSettings[n].ID == id)
19713
0
            return &dc->NodesSettings[n];
19714
0
    return NULL;
19715
0
}
19716
19717
// Clear settings data
19718
static void ImGui::DockSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
19719
0
{
19720
0
    ImGuiDockContext* dc = &ctx->DockContext;
19721
0
    dc->NodesSettings.clear();
19722
0
    DockContextClearNodes(ctx, 0, true);
19723
0
}
19724
19725
// Recreate nodes based on settings data
19726
static void ImGui::DockSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
19727
0
{
19728
    // Prune settings at boot time only
19729
0
    ImGuiDockContext* dc = &ctx->DockContext;
19730
0
    if (ctx->Windows.Size == 0)
19731
0
        DockContextPruneUnusedSettingsNodes(ctx);
19732
0
    DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size);
19733
0
    DockContextBuildAddWindowsToNodes(ctx, 0);
19734
0
}
19735
19736
static void* ImGui::DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
19737
0
{
19738
0
    if (strcmp(name, "Data") != 0)
19739
0
        return NULL;
19740
0
    return (void*)1;
19741
0
}
19742
19743
static void ImGui::DockSettingsHandler_ReadLine(ImGuiContext* ctx, ImGuiSettingsHandler*, void*, const char* line)
19744
0
{
19745
0
    char c = 0;
19746
0
    int x = 0, y = 0;
19747
0
    int r = 0;
19748
19749
    // Parsing, e.g.
19750
    // " DockNode   ID=0x00000001 Pos=383,193 Size=201,322 Split=Y,0.506 "
19751
    // "   DockNode ID=0x00000002 Parent=0x00000001 "
19752
    // Important: this code expect currently fields in a fixed order.
19753
0
    ImGuiDockNodeSettings node;
19754
0
    line = ImStrSkipBlank(line);
19755
0
    if      (strncmp(line, "DockNode", 8) == 0)  { line = ImStrSkipBlank(line + strlen("DockNode")); }
19756
0
    else if (strncmp(line, "DockSpace", 9) == 0) { line = ImStrSkipBlank(line + strlen("DockSpace")); node.Flags |= ImGuiDockNodeFlags_DockSpace; }
19757
0
    else return;
19758
0
    if (sscanf(line, "ID=0x%08X%n",      &node.ID, &r) == 1)            { line += r; } else return;
19759
0
    if (sscanf(line, " Parent=0x%08X%n", &node.ParentNodeId, &r) == 1)  { line += r; if (node.ParentNodeId == 0) return; }
19760
0
    if (sscanf(line, " Window=0x%08X%n", &node.ParentWindowId, &r) ==1) { line += r; if (node.ParentWindowId == 0) return; }
19761
0
    if (node.ParentNodeId == 0)
19762
0
    {
19763
0
        if (sscanf(line, " Pos=%i,%i%n",  &x, &y, &r) == 2)         { line += r; node.Pos = ImVec2ih((short)x, (short)y); } else return;
19764
0
        if (sscanf(line, " Size=%i,%i%n", &x, &y, &r) == 2)         { line += r; node.Size = ImVec2ih((short)x, (short)y); } else return;
19765
0
    }
19766
0
    else
19767
0
    {
19768
0
        if (sscanf(line, " SizeRef=%i,%i%n", &x, &y, &r) == 2)      { line += r; node.SizeRef = ImVec2ih((short)x, (short)y); }
19769
0
    }
19770
0
    if (sscanf(line, " Split=%c%n", &c, &r) == 1)                   { line += r; if (c == 'X') node.SplitAxis = ImGuiAxis_X; else if (c == 'Y') node.SplitAxis = ImGuiAxis_Y; }
19771
0
    if (sscanf(line, " NoResize=%d%n", &x, &r) == 1)                { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoResize; }
19772
0
    if (sscanf(line, " CentralNode=%d%n", &x, &r) == 1)             { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_CentralNode; }
19773
0
    if (sscanf(line, " NoTabBar=%d%n", &x, &r) == 1)                { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoTabBar; }
19774
0
    if (sscanf(line, " HiddenTabBar=%d%n", &x, &r) == 1)            { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_HiddenTabBar; }
19775
0
    if (sscanf(line, " NoWindowMenuButton=%d%n", &x, &r) == 1)      { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoWindowMenuButton; }
19776
0
    if (sscanf(line, " NoCloseButton=%d%n", &x, &r) == 1)           { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoCloseButton; }
19777
0
    if (sscanf(line, " Selected=0x%08X%n", &node.SelectedTabId,&r) == 1) { line += r; }
19778
0
    if (node.ParentNodeId != 0)
19779
0
        if (ImGuiDockNodeSettings* parent_settings = DockSettingsFindNodeSettings(ctx, node.ParentNodeId))
19780
0
            node.Depth = parent_settings->Depth + 1;
19781
0
    ctx->DockContext.NodesSettings.push_back(node);
19782
0
}
19783
19784
static void DockSettingsHandler_DockNodeToSettings(ImGuiDockContext* dc, ImGuiDockNode* node, int depth)
19785
0
{
19786
0
    ImGuiDockNodeSettings node_settings;
19787
0
    IM_ASSERT(depth < (1 << (sizeof(node_settings.Depth) << 3)));
19788
0
    node_settings.ID = node->ID;
19789
0
    node_settings.ParentNodeId = node->ParentNode ? node->ParentNode->ID : 0;
19790
0
    node_settings.ParentWindowId = (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow) ? node->HostWindow->ParentWindow->ID : 0;
19791
0
    node_settings.SelectedTabId = node->SelectedTabId;
19792
0
    node_settings.SplitAxis = (signed char)(node->IsSplitNode() ? node->SplitAxis : ImGuiAxis_None);
19793
0
    node_settings.Depth = (char)depth;
19794
0
    node_settings.Flags = (node->LocalFlags & ImGuiDockNodeFlags_SavedFlagsMask_);
19795
0
    node_settings.Pos = ImVec2ih(node->Pos);
19796
0
    node_settings.Size = ImVec2ih(node->Size);
19797
0
    node_settings.SizeRef = ImVec2ih(node->SizeRef);
19798
0
    dc->NodesSettings.push_back(node_settings);
19799
0
    if (node->ChildNodes[0])
19800
0
        DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[0], depth + 1);
19801
0
    if (node->ChildNodes[1])
19802
0
        DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[1], depth + 1);
19803
0
}
19804
19805
static void ImGui::DockSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
19806
0
{
19807
0
    ImGuiContext& g = *ctx;
19808
0
    ImGuiDockContext* dc = &ctx->DockContext;
19809
0
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
19810
0
        return;
19811
19812
    // Gather settings data
19813
    // (unlike our windows settings, because nodes are always built we can do a full rewrite of the SettingsNode buffer)
19814
0
    dc->NodesSettings.resize(0);
19815
0
    dc->NodesSettings.reserve(dc->Nodes.Data.Size);
19816
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
19817
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
19818
0
            if (node->IsRootNode())
19819
0
                DockSettingsHandler_DockNodeToSettings(dc, node, 0);
19820
19821
0
    int max_depth = 0;
19822
0
    for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
19823
0
        max_depth = ImMax((int)dc->NodesSettings[node_n].Depth, max_depth);
19824
19825
    // Write to text buffer
19826
0
    buf->appendf("[%s][Data]\n", handler->TypeName);
19827
0
    for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
19828
0
    {
19829
0
        const int line_start_pos = buf->size(); (void)line_start_pos;
19830
0
        const ImGuiDockNodeSettings* node_settings = &dc->NodesSettings[node_n];
19831
0
        buf->appendf("%*s%s%*s", node_settings->Depth * 2, "", (node_settings->Flags & ImGuiDockNodeFlags_DockSpace) ? "DockSpace" : "DockNode ", (max_depth - node_settings->Depth) * 2, "");  // Text align nodes to facilitate looking at .ini file
19832
0
        buf->appendf(" ID=0x%08X", node_settings->ID);
19833
0
        if (node_settings->ParentNodeId)
19834
0
        {
19835
0
            buf->appendf(" Parent=0x%08X SizeRef=%d,%d", node_settings->ParentNodeId, node_settings->SizeRef.x, node_settings->SizeRef.y);
19836
0
        }
19837
0
        else
19838
0
        {
19839
0
            if (node_settings->ParentWindowId)
19840
0
                buf->appendf(" Window=0x%08X", node_settings->ParentWindowId);
19841
0
            buf->appendf(" Pos=%d,%d Size=%d,%d", node_settings->Pos.x, node_settings->Pos.y, node_settings->Size.x, node_settings->Size.y);
19842
0
        }
19843
0
        if (node_settings->SplitAxis != ImGuiAxis_None)
19844
0
            buf->appendf(" Split=%c", (node_settings->SplitAxis == ImGuiAxis_X) ? 'X' : 'Y');
19845
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoResize)
19846
0
            buf->appendf(" NoResize=1");
19847
0
        if (node_settings->Flags & ImGuiDockNodeFlags_CentralNode)
19848
0
            buf->appendf(" CentralNode=1");
19849
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoTabBar)
19850
0
            buf->appendf(" NoTabBar=1");
19851
0
        if (node_settings->Flags & ImGuiDockNodeFlags_HiddenTabBar)
19852
0
            buf->appendf(" HiddenTabBar=1");
19853
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoWindowMenuButton)
19854
0
            buf->appendf(" NoWindowMenuButton=1");
19855
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoCloseButton)
19856
0
            buf->appendf(" NoCloseButton=1");
19857
0
        if (node_settings->SelectedTabId)
19858
0
            buf->appendf(" Selected=0x%08X", node_settings->SelectedTabId);
19859
19860
        // [DEBUG] Include comments in the .ini file to ease debugging (this makes saving slower!)
19861
0
        if (g.IO.ConfigDebugIniSettings)
19862
0
            if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_settings->ID))
19863
0
            {
19864
0
                buf->appendf("%*s", ImMax(2, (line_start_pos + 92) - buf->size()), "");     // Align everything
19865
0
                if (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow)
19866
0
                    buf->appendf(" ; in '%s'", node->HostWindow->ParentWindow->Name);
19867
                // Iterate settings so we can give info about windows that didn't exist during the session.
19868
0
                int contains_window = 0;
19869
0
                for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19870
0
                    if (settings->DockId == node_settings->ID)
19871
0
                    {
19872
0
                        if (contains_window++ == 0)
19873
0
                            buf->appendf(" ; contains ");
19874
0
                        buf->appendf("'%s' ", settings->GetName());
19875
0
                    }
19876
0
            }
19877
19878
0
        buf->appendf("\n");
19879
0
    }
19880
0
    buf->appendf("\n");
19881
0
}
19882
19883
19884
//-----------------------------------------------------------------------------
19885
// [SECTION] PLATFORM DEPENDENT HELPERS
19886
//-----------------------------------------------------------------------------
19887
// - Default clipboard handlers
19888
// - Default shell function handlers
19889
// - Default IME handlers
19890
//-----------------------------------------------------------------------------
19891
19892
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS)
19893
19894
#ifdef _MSC_VER
19895
#pragma comment(lib, "user32")
19896
#pragma comment(lib, "kernel32")
19897
#endif
19898
19899
// Win32 clipboard implementation
19900
// We use g.ClipboardHandlerData for temporary storage to ensure it is freed on Shutdown()
19901
static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
19902
{
19903
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
19904
    g.ClipboardHandlerData.clear();
19905
    if (!::OpenClipboard(NULL))
19906
        return NULL;
19907
    HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT);
19908
    if (wbuf_handle == NULL)
19909
    {
19910
        ::CloseClipboard();
19911
        return NULL;
19912
    }
19913
    if (const WCHAR* wbuf_global = (const WCHAR*)::GlobalLock(wbuf_handle))
19914
    {
19915
        int buf_len = ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, NULL, 0, NULL, NULL);
19916
        g.ClipboardHandlerData.resize(buf_len);
19917
        ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, g.ClipboardHandlerData.Data, buf_len, NULL, NULL);
19918
    }
19919
    ::GlobalUnlock(wbuf_handle);
19920
    ::CloseClipboard();
19921
    return g.ClipboardHandlerData.Data;
19922
}
19923
19924
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
19925
{
19926
    if (!::OpenClipboard(NULL))
19927
        return;
19928
    const int wbuf_length = ::MultiByteToWideChar(CP_UTF8, 0, text, -1, NULL, 0);
19929
    HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(WCHAR));
19930
    if (wbuf_handle == NULL)
19931
    {
19932
        ::CloseClipboard();
19933
        return;
19934
    }
19935
    WCHAR* wbuf_global = (WCHAR*)::GlobalLock(wbuf_handle);
19936
    ::MultiByteToWideChar(CP_UTF8, 0, text, -1, wbuf_global, wbuf_length);
19937
    ::GlobalUnlock(wbuf_handle);
19938
    ::EmptyClipboard();
19939
    if (::SetClipboardData(CF_UNICODETEXT, wbuf_handle) == NULL)
19940
        ::GlobalFree(wbuf_handle);
19941
    ::CloseClipboard();
19942
}
19943
19944
#elif defined(__APPLE__) && TARGET_OS_OSX && defined(IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS)
19945
19946
#include <Carbon/Carbon.h>  // Use old API to avoid need for separate .mm file
19947
static PasteboardRef main_clipboard = 0;
19948
19949
// OSX clipboard implementation
19950
// If you enable this you will need to add '-framework ApplicationServices' to your linker command-line!
19951
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
19952
{
19953
    if (!main_clipboard)
19954
        PasteboardCreate(kPasteboardClipboard, &main_clipboard);
19955
    PasteboardClear(main_clipboard);
19956
    CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)text, strlen(text));
19957
    if (cf_data)
19958
    {
19959
        PasteboardPutItemFlavor(main_clipboard, (PasteboardItemID)1, CFSTR("public.utf8-plain-text"), cf_data, 0);
19960
        CFRelease(cf_data);
19961
    }
19962
}
19963
19964
static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
19965
{
19966
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
19967
    if (!main_clipboard)
19968
        PasteboardCreate(kPasteboardClipboard, &main_clipboard);
19969
    PasteboardSynchronize(main_clipboard);
19970
19971
    ItemCount item_count = 0;
19972
    PasteboardGetItemCount(main_clipboard, &item_count);
19973
    for (ItemCount i = 0; i < item_count; i++)
19974
    {
19975
        PasteboardItemID item_id = 0;
19976
        PasteboardGetItemIdentifier(main_clipboard, i + 1, &item_id);
19977
        CFArrayRef flavor_type_array = 0;
19978
        PasteboardCopyItemFlavors(main_clipboard, item_id, &flavor_type_array);
19979
        for (CFIndex j = 0, nj = CFArrayGetCount(flavor_type_array); j < nj; j++)
19980
        {
19981
            CFDataRef cf_data;
19982
            if (PasteboardCopyItemFlavorData(main_clipboard, item_id, CFSTR("public.utf8-plain-text"), &cf_data) == noErr)
19983
            {
19984
                g.ClipboardHandlerData.clear();
19985
                int length = (int)CFDataGetLength(cf_data);
19986
                g.ClipboardHandlerData.resize(length + 1);
19987
                CFDataGetBytes(cf_data, CFRangeMake(0, length), (UInt8*)g.ClipboardHandlerData.Data);
19988
                g.ClipboardHandlerData[length] = 0;
19989
                CFRelease(cf_data);
19990
                return g.ClipboardHandlerData.Data;
19991
            }
19992
        }
19993
    }
19994
    return NULL;
19995
}
19996
19997
#else
19998
19999
// Local Dear ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers.
20000
static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
20001
0
{
20002
0
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
20003
0
    return g.ClipboardHandlerData.empty() ? NULL : g.ClipboardHandlerData.begin();
20004
0
}
20005
20006
static void SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text)
20007
0
{
20008
0
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
20009
0
    g.ClipboardHandlerData.clear();
20010
0
    const char* text_end = text + strlen(text);
20011
0
    g.ClipboardHandlerData.resize((int)(text_end - text) + 1);
20012
0
    memcpy(&g.ClipboardHandlerData[0], text, (size_t)(text_end - text));
20013
0
    g.ClipboardHandlerData[(int)(text_end - text)] = 0;
20014
0
}
20015
20016
#endif // Default clipboard handlers
20017
20018
//-----------------------------------------------------------------------------
20019
20020
#ifndef IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
20021
#if defined(__APPLE__) && TARGET_OS_IPHONE
20022
#define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
20023
#endif
20024
20025
#if defined(_WIN32) && defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
20026
#define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
20027
#endif
20028
#endif
20029
20030
#ifndef IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
20031
#ifdef _WIN32
20032
#include <shellapi.h>   // ShellExecuteA()
20033
#ifdef _MSC_VER
20034
#pragma comment(lib, "shell32")
20035
#endif
20036
static bool PlatformOpenInShellFn_DefaultImpl(ImGuiContext*, const char* path)
20037
{
20038
    return (INT_PTR)::ShellExecuteA(NULL, "open", path, NULL, NULL, SW_SHOWDEFAULT) > 32;
20039
}
20040
#else
20041
#include <sys/wait.h>
20042
#include <unistd.h>
20043
static bool PlatformOpenInShellFn_DefaultImpl(ImGuiContext*, const char* path)
20044
0
{
20045
#if defined(__APPLE__)
20046
    const char* args[] { "open", "--", path, NULL };
20047
#else
20048
0
    const char* args[] { "xdg-open", path, NULL };
20049
0
#endif
20050
0
    pid_t pid = fork();
20051
0
    if (pid < 0)
20052
0
        return false;
20053
0
    if (!pid)
20054
0
    {
20055
0
        execvp(args[0], const_cast<char **>(args));
20056
0
        exit(-1);
20057
0
    }
20058
0
    else
20059
0
    {
20060
0
        int status;
20061
0
        waitpid(pid, &status, 0);
20062
0
        return WEXITSTATUS(status) == 0;
20063
0
    }
20064
0
}
20065
#endif
20066
#else
20067
static bool PlatformOpenInShellFn_DefaultImpl(ImGuiContext*, const char*) { return false; }
20068
#endif // Default shell handlers
20069
20070
//-----------------------------------------------------------------------------
20071
20072
// Win32 API IME support (for Asian languages, etc.)
20073
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
20074
20075
#include <imm.h>
20076
#ifdef _MSC_VER
20077
#pragma comment(lib, "imm32")
20078
#endif
20079
20080
static void PlatformSetImeDataFn_DefaultImpl(ImGuiContext*, ImGuiViewport* viewport, ImGuiPlatformImeData* data)
20081
{
20082
    // Notify OS Input Method Editor of text input position
20083
    HWND hwnd = (HWND)viewport->PlatformHandleRaw;
20084
    if (hwnd == 0)
20085
        return;
20086
20087
    //::ImmAssociateContextEx(hwnd, NULL, data->WantVisible ? IACE_DEFAULT : 0);
20088
    if (HIMC himc = ::ImmGetContext(hwnd))
20089
    {
20090
        COMPOSITIONFORM composition_form = {};
20091
        composition_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x);
20092
        composition_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y);
20093
        composition_form.dwStyle = CFS_FORCE_POSITION;
20094
        ::ImmSetCompositionWindow(himc, &composition_form);
20095
        CANDIDATEFORM candidate_form = {};
20096
        candidate_form.dwStyle = CFS_CANDIDATEPOS;
20097
        candidate_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x);
20098
        candidate_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y);
20099
        ::ImmSetCandidateWindow(himc, &candidate_form);
20100
        ::ImmReleaseContext(hwnd, himc);
20101
    }
20102
}
20103
20104
#else
20105
20106
0
static void PlatformSetImeDataFn_DefaultImpl(ImGuiContext*, ImGuiViewport*, ImGuiPlatformImeData*) {}
20107
20108
#endif // Default IME handlers
20109
20110
//-----------------------------------------------------------------------------
20111
// [SECTION] METRICS/DEBUGGER WINDOW
20112
//-----------------------------------------------------------------------------
20113
// - DebugRenderViewportThumbnail() [Internal]
20114
// - RenderViewportsThumbnails() [Internal]
20115
// - DebugTextEncoding()
20116
// - MetricsHelpMarker() [Internal]
20117
// - ShowFontAtlas() [Internal]
20118
// - ShowMetricsWindow()
20119
// - DebugNodeColumns() [Internal]
20120
// - DebugNodeDockNode() [Internal]
20121
// - DebugNodeDrawList() [Internal]
20122
// - DebugNodeDrawCmdShowMeshAndBoundingBox() [Internal]
20123
// - DebugNodeFont() [Internal]
20124
// - DebugNodeFontGlyph() [Internal]
20125
// - DebugNodeStorage() [Internal]
20126
// - DebugNodeTabBar() [Internal]
20127
// - DebugNodeViewport() [Internal]
20128
// - DebugNodeWindow() [Internal]
20129
// - DebugNodeWindowSettings() [Internal]
20130
// - DebugNodeWindowsList() [Internal]
20131
// - DebugNodeWindowsListByBeginStackParent() [Internal]
20132
//-----------------------------------------------------------------------------
20133
20134
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
20135
20136
void ImGui::DebugRenderViewportThumbnail(ImDrawList* draw_list, ImGuiViewportP* viewport, const ImRect& bb)
20137
0
{
20138
0
    ImGuiContext& g = *GImGui;
20139
0
    ImGuiWindow* window = g.CurrentWindow;
20140
20141
0
    ImVec2 scale = bb.GetSize() / viewport->Size;
20142
0
    ImVec2 off = bb.Min - viewport->Pos * scale;
20143
0
    float alpha_mul = (viewport->Flags & ImGuiViewportFlags_IsMinimized) ? 0.30f : 1.00f;
20144
0
    window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul * 0.40f));
20145
0
    for (ImGuiWindow* thumb_window : g.Windows)
20146
0
    {
20147
0
        if (!thumb_window->WasActive || (thumb_window->Flags & ImGuiWindowFlags_ChildWindow))
20148
0
            continue;
20149
0
        if (thumb_window->Viewport != viewport)
20150
0
            continue;
20151
20152
0
        ImRect thumb_r = thumb_window->Rect();
20153
0
        ImRect title_r = thumb_window->TitleBarRect();
20154
0
        thumb_r = ImRect(ImTrunc(off + thumb_r.Min * scale), ImTrunc(off +  thumb_r.Max * scale));
20155
0
        title_r = ImRect(ImTrunc(off + title_r.Min * scale), ImTrunc(off +  ImVec2(title_r.Max.x, title_r.Min.y + title_r.GetHeight() * 3.0f) * scale)); // Exaggerate title bar height
20156
0
        thumb_r.ClipWithFull(bb);
20157
0
        title_r.ClipWithFull(bb);
20158
0
        const bool window_is_focused = (g.NavWindow && thumb_window->RootWindowForTitleBarHighlight == g.NavWindow->RootWindowForTitleBarHighlight);
20159
0
        window->DrawList->AddRectFilled(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_WindowBg, alpha_mul));
20160
0
        window->DrawList->AddRectFilled(title_r.Min, title_r.Max, GetColorU32(window_is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg, alpha_mul));
20161
0
        window->DrawList->AddRect(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
20162
0
        window->DrawList->AddText(g.Font, g.FontSize * 1.0f, title_r.Min, GetColorU32(ImGuiCol_Text, alpha_mul), thumb_window->Name, FindRenderedTextEnd(thumb_window->Name));
20163
0
    }
20164
0
    draw_list->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
20165
0
    if (viewport->ID == g.DebugMetricsConfig.HighlightViewportID)
20166
0
        window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
20167
0
}
20168
20169
static void RenderViewportsThumbnails()
20170
0
{
20171
0
    ImGuiContext& g = *GImGui;
20172
0
    ImGuiWindow* window = g.CurrentWindow;
20173
20174
    // Draw monitor and calculate their boundaries
20175
0
    float SCALE = 1.0f / 8.0f;
20176
0
    ImRect bb_full(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
20177
0
    for (ImGuiPlatformMonitor& monitor : g.PlatformIO.Monitors)
20178
0
        bb_full.Add(ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize));
20179
0
    ImVec2 p = window->DC.CursorPos;
20180
0
    ImVec2 off = p - bb_full.Min * SCALE;
20181
0
    for (ImGuiPlatformMonitor& monitor : g.PlatformIO.Monitors)
20182
0
    {
20183
0
        ImRect monitor_draw_bb(off + (monitor.MainPos) * SCALE, off + (monitor.MainPos + monitor.MainSize) * SCALE);
20184
0
        window->DrawList->AddRect(monitor_draw_bb.Min, monitor_draw_bb.Max, (g.DebugMetricsConfig.HighlightMonitorIdx == g.PlatformIO.Monitors.index_from_ptr(&monitor)) ? IM_COL32(255, 255, 0, 255) : ImGui::GetColorU32(ImGuiCol_Border), 4.0f);
20185
0
        window->DrawList->AddRectFilled(monitor_draw_bb.Min, monitor_draw_bb.Max, ImGui::GetColorU32(ImGuiCol_Border, 0.10f), 4.0f);
20186
0
    }
20187
20188
    // Draw viewports
20189
0
    for (ImGuiViewportP* viewport : g.Viewports)
20190
0
    {
20191
0
        ImRect viewport_draw_bb(off + (viewport->Pos) * SCALE, off + (viewport->Pos + viewport->Size) * SCALE);
20192
0
        ImGui::DebugRenderViewportThumbnail(window->DrawList, viewport, viewport_draw_bb);
20193
0
    }
20194
0
    ImGui::Dummy(bb_full.GetSize() * SCALE);
20195
0
}
20196
20197
static int IMGUI_CDECL ViewportComparerByLastFocusedStampCount(const void* lhs, const void* rhs)
20198
0
{
20199
0
    const ImGuiViewportP* a = *(const ImGuiViewportP* const*)lhs;
20200
0
    const ImGuiViewportP* b = *(const ImGuiViewportP* const*)rhs;
20201
0
    return b->LastFocusedStampCount - a->LastFocusedStampCount;
20202
0
}
20203
20204
// Draw an arbitrary US keyboard layout to visualize translated keys
20205
void ImGui::DebugRenderKeyboardPreview(ImDrawList* draw_list)
20206
0
{
20207
0
    const float scale = ImGui::GetFontSize() / 13.0f;
20208
0
    const ImVec2 key_size = ImVec2(35.0f, 35.0f) * scale;
20209
0
    const float  key_rounding = 3.0f * scale;
20210
0
    const ImVec2 key_face_size = ImVec2(25.0f, 25.0f) * scale;
20211
0
    const ImVec2 key_face_pos = ImVec2(5.0f, 3.0f) * scale;
20212
0
    const float  key_face_rounding = 2.0f * scale;
20213
0
    const ImVec2 key_label_pos = ImVec2(7.0f, 4.0f) * scale;
20214
0
    const ImVec2 key_step = ImVec2(key_size.x - 1.0f, key_size.y - 1.0f);
20215
0
    const float  key_row_offset = 9.0f * scale;
20216
20217
0
    ImVec2 board_min = GetCursorScreenPos();
20218
0
    ImVec2 board_max = ImVec2(board_min.x + 3 * key_step.x + 2 * key_row_offset + 10.0f, board_min.y + 3 * key_step.y + 10.0f);
20219
0
    ImVec2 start_pos = ImVec2(board_min.x + 5.0f - key_step.x, board_min.y);
20220
20221
0
    struct KeyLayoutData { int Row, Col; const char* Label; ImGuiKey Key; };
20222
0
    const KeyLayoutData keys_to_display[] =
20223
0
    {
20224
0
        { 0, 0, "", ImGuiKey_Tab },      { 0, 1, "Q", ImGuiKey_Q }, { 0, 2, "W", ImGuiKey_W }, { 0, 3, "E", ImGuiKey_E }, { 0, 4, "R", ImGuiKey_R },
20225
0
        { 1, 0, "", ImGuiKey_CapsLock }, { 1, 1, "A", ImGuiKey_A }, { 1, 2, "S", ImGuiKey_S }, { 1, 3, "D", ImGuiKey_D }, { 1, 4, "F", ImGuiKey_F },
20226
0
        { 2, 0, "", ImGuiKey_LeftShift },{ 2, 1, "Z", ImGuiKey_Z }, { 2, 2, "X", ImGuiKey_X }, { 2, 3, "C", ImGuiKey_C }, { 2, 4, "V", ImGuiKey_V }
20227
0
    };
20228
20229
    // Elements rendered manually via ImDrawList API are not clipped automatically.
20230
    // While not strictly necessary, here IsItemVisible() is used to avoid rendering these shapes when they are out of view.
20231
0
    Dummy(board_max - board_min);
20232
0
    if (!IsItemVisible())
20233
0
        return;
20234
0
    draw_list->PushClipRect(board_min, board_max, true);
20235
0
    for (int n = 0; n < IM_ARRAYSIZE(keys_to_display); n++)
20236
0
    {
20237
0
        const KeyLayoutData* key_data = &keys_to_display[n];
20238
0
        ImVec2 key_min = ImVec2(start_pos.x + key_data->Col * key_step.x + key_data->Row * key_row_offset, start_pos.y + key_data->Row * key_step.y);
20239
0
        ImVec2 key_max = key_min + key_size;
20240
0
        draw_list->AddRectFilled(key_min, key_max, IM_COL32(204, 204, 204, 255), key_rounding);
20241
0
        draw_list->AddRect(key_min, key_max, IM_COL32(24, 24, 24, 255), key_rounding);
20242
0
        ImVec2 face_min = ImVec2(key_min.x + key_face_pos.x, key_min.y + key_face_pos.y);
20243
0
        ImVec2 face_max = ImVec2(face_min.x + key_face_size.x, face_min.y + key_face_size.y);
20244
0
        draw_list->AddRect(face_min, face_max, IM_COL32(193, 193, 193, 255), key_face_rounding, ImDrawFlags_None, 2.0f);
20245
0
        draw_list->AddRectFilled(face_min, face_max, IM_COL32(252, 252, 252, 255), key_face_rounding);
20246
0
        ImVec2 label_min = ImVec2(key_min.x + key_label_pos.x, key_min.y + key_label_pos.y);
20247
0
        draw_list->AddText(label_min, IM_COL32(64, 64, 64, 255), key_data->Label);
20248
0
        if (IsKeyDown(key_data->Key))
20249
0
            draw_list->AddRectFilled(key_min, key_max, IM_COL32(255, 0, 0, 128), key_rounding);
20250
0
    }
20251
0
    draw_list->PopClipRect();
20252
0
}
20253
20254
// Helper tool to diagnose between text encoding issues and font loading issues. Pass your UTF-8 string and verify that there are correct.
20255
void ImGui::DebugTextEncoding(const char* str)
20256
0
{
20257
0
    Text("Text: \"%s\"", str);
20258
0
    if (!BeginTable("##DebugTextEncoding", 4, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Resizable))
20259
0
        return;
20260
0
    TableSetupColumn("Offset");
20261
0
    TableSetupColumn("UTF-8");
20262
0
    TableSetupColumn("Glyph");
20263
0
    TableSetupColumn("Codepoint");
20264
0
    TableHeadersRow();
20265
0
    for (const char* p = str; *p != 0; )
20266
0
    {
20267
0
        unsigned int c;
20268
0
        const int c_utf8_len = ImTextCharFromUtf8(&c, p, NULL);
20269
0
        TableNextColumn();
20270
0
        Text("%d", (int)(p - str));
20271
0
        TableNextColumn();
20272
0
        for (int byte_index = 0; byte_index < c_utf8_len; byte_index++)
20273
0
        {
20274
0
            if (byte_index > 0)
20275
0
                SameLine();
20276
0
            Text("0x%02X", (int)(unsigned char)p[byte_index]);
20277
0
        }
20278
0
        TableNextColumn();
20279
0
        if (GetFont()->FindGlyphNoFallback((ImWchar)c))
20280
0
            TextUnformatted(p, p + c_utf8_len);
20281
0
        else
20282
0
            TextUnformatted((c == IM_UNICODE_CODEPOINT_INVALID) ? "[invalid]" : "[missing]");
20283
0
        TableNextColumn();
20284
0
        Text("U+%04X", (int)c);
20285
0
        p += c_utf8_len;
20286
0
    }
20287
0
    EndTable();
20288
0
}
20289
20290
static void DebugFlashStyleColorStop()
20291
0
{
20292
0
    ImGuiContext& g = *GImGui;
20293
0
    if (g.DebugFlashStyleColorIdx != ImGuiCol_COUNT)
20294
0
        g.Style.Colors[g.DebugFlashStyleColorIdx] = g.DebugFlashStyleColorBackup;
20295
0
    g.DebugFlashStyleColorIdx = ImGuiCol_COUNT;
20296
0
}
20297
20298
// Flash a given style color for some + inhibit modifications of this color via PushStyleColor() calls.
20299
void ImGui::DebugFlashStyleColor(ImGuiCol idx)
20300
0
{
20301
0
    ImGuiContext& g = *GImGui;
20302
0
    DebugFlashStyleColorStop();
20303
0
    g.DebugFlashStyleColorTime = 0.5f;
20304
0
    g.DebugFlashStyleColorIdx = idx;
20305
0
    g.DebugFlashStyleColorBackup = g.Style.Colors[idx];
20306
0
}
20307
20308
void ImGui::UpdateDebugToolFlashStyleColor()
20309
84.9k
{
20310
84.9k
    ImGuiContext& g = *GImGui;
20311
84.9k
    if (g.DebugFlashStyleColorTime <= 0.0f)
20312
84.9k
        return;
20313
0
    ColorConvertHSVtoRGB(cosf(g.DebugFlashStyleColorTime * 6.0f) * 0.5f + 0.5f, 0.5f, 0.5f, g.Style.Colors[g.DebugFlashStyleColorIdx].x, g.Style.Colors[g.DebugFlashStyleColorIdx].y, g.Style.Colors[g.DebugFlashStyleColorIdx].z);
20314
0
    g.Style.Colors[g.DebugFlashStyleColorIdx].w = 1.0f;
20315
0
    if ((g.DebugFlashStyleColorTime -= g.IO.DeltaTime) <= 0.0f)
20316
0
        DebugFlashStyleColorStop();
20317
0
}
20318
20319
// Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds.
20320
static void MetricsHelpMarker(const char* desc)
20321
0
{
20322
0
    ImGui::TextDisabled("(?)");
20323
0
    if (ImGui::BeginItemTooltip())
20324
0
    {
20325
0
        ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
20326
0
        ImGui::TextUnformatted(desc);
20327
0
        ImGui::PopTextWrapPos();
20328
0
        ImGui::EndTooltip();
20329
0
    }
20330
0
}
20331
20332
// [DEBUG] List fonts in a font atlas and display its texture
20333
void ImGui::ShowFontAtlas(ImFontAtlas* atlas)
20334
0
{
20335
0
    for (ImFont* font : atlas->Fonts)
20336
0
    {
20337
0
        PushID(font);
20338
0
        DebugNodeFont(font);
20339
0
        PopID();
20340
0
    }
20341
0
    if (TreeNode("Font Atlas", "Font Atlas (%dx%d pixels)", atlas->TexWidth, atlas->TexHeight))
20342
0
    {
20343
0
        ImGuiContext& g = *GImGui;
20344
0
        ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
20345
0
        Checkbox("Tint with Text Color", &cfg->ShowAtlasTintedWithTextColor); // Using text color ensure visibility of core atlas data, but will alter custom colored icons
20346
0
        ImVec4 tint_col = cfg->ShowAtlasTintedWithTextColor ? GetStyleColorVec4(ImGuiCol_Text) : ImVec4(1.0f, 1.0f, 1.0f, 1.0f);
20347
0
        ImVec4 border_col = GetStyleColorVec4(ImGuiCol_Border);
20348
0
        Image(atlas->TexID, ImVec2((float)atlas->TexWidth, (float)atlas->TexHeight), ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), tint_col, border_col);
20349
0
        TreePop();
20350
0
    }
20351
0
}
20352
20353
void ImGui::ShowMetricsWindow(bool* p_open)
20354
0
{
20355
0
    ImGuiContext& g = *GImGui;
20356
0
    ImGuiIO& io = g.IO;
20357
0
    ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
20358
0
    if (cfg->ShowDebugLog)
20359
0
        ShowDebugLogWindow(&cfg->ShowDebugLog);
20360
0
    if (cfg->ShowIDStackTool)
20361
0
        ShowIDStackToolWindow(&cfg->ShowIDStackTool);
20362
20363
0
    if (!Begin("Dear ImGui Metrics/Debugger", p_open) || GetCurrentWindow()->BeginCount > 1)
20364
0
    {
20365
0
        End();
20366
0
        return;
20367
0
    }
20368
20369
    // [DEBUG] Clear debug breaks hooks after exactly one cycle.
20370
0
    DebugBreakClearData();
20371
20372
    // Basic info
20373
0
    Text("Dear ImGui %s", GetVersion());
20374
0
    if (g.ContextName[0] != 0)
20375
0
    {
20376
0
        SameLine();
20377
0
        Text("(Context Name: \"%s\")", g.ContextName);
20378
0
    }
20379
0
    Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
20380
0
    Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3);
20381
0
    Text("%d visible windows, %d current allocations", io.MetricsRenderWindows, g.DebugAllocInfo.TotalAllocCount - g.DebugAllocInfo.TotalFreeCount);
20382
    //SameLine(); if (SmallButton("GC")) { g.GcCompactAll = true; }
20383
20384
0
    Separator();
20385
20386
    // Debugging enums
20387
0
    enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Content, WRT_ContentIdeal, WRT_ContentRegionRect, WRT_Count }; // Windows Rect Type
20388
0
    const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentIdeal", "ContentRegionRect" };
20389
0
    enum { TRT_OuterRect, TRT_InnerRect, TRT_WorkRect, TRT_HostClipRect, TRT_InnerClipRect, TRT_BackgroundClipRect, TRT_ColumnsRect, TRT_ColumnsWorkRect, TRT_ColumnsClipRect, TRT_ColumnsContentHeadersUsed, TRT_ColumnsContentHeadersIdeal, TRT_ColumnsContentFrozen, TRT_ColumnsContentUnfrozen, TRT_Count }; // Tables Rect Type
20390
0
    const char* trt_rects_names[TRT_Count] = { "OuterRect", "InnerRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsWorkRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersIdeal", "ColumnsContentFrozen", "ColumnsContentUnfrozen" };
20391
0
    if (cfg->ShowWindowsRectsType < 0)
20392
0
        cfg->ShowWindowsRectsType = WRT_WorkRect;
20393
0
    if (cfg->ShowTablesRectsType < 0)
20394
0
        cfg->ShowTablesRectsType = TRT_WorkRect;
20395
20396
0
    struct Funcs
20397
0
    {
20398
0
        static ImRect GetTableRect(ImGuiTable* table, int rect_type, int n)
20399
0
        {
20400
0
            ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent); // Always using last submitted instance
20401
0
            if (rect_type == TRT_OuterRect)                     { return table->OuterRect; }
20402
0
            else if (rect_type == TRT_InnerRect)                { return table->InnerRect; }
20403
0
            else if (rect_type == TRT_WorkRect)                 { return table->WorkRect; }
20404
0
            else if (rect_type == TRT_HostClipRect)             { return table->HostClipRect; }
20405
0
            else if (rect_type == TRT_InnerClipRect)            { return table->InnerClipRect; }
20406
0
            else if (rect_type == TRT_BackgroundClipRect)       { return table->BgClipRect; }
20407
0
            else if (rect_type == TRT_ColumnsRect)              { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y, c->MaxX, table->InnerClipRect.Min.y + table_instance->LastOuterHeight); }
20408
0
            else if (rect_type == TRT_ColumnsWorkRect)          { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->WorkRect.Min.y, c->WorkMaxX, table->WorkRect.Max.y); }
20409
0
            else if (rect_type == TRT_ColumnsClipRect)          { ImGuiTableColumn* c = &table->Columns[n]; return c->ClipRect; }
20410
0
            else if (rect_type == TRT_ColumnsContentHeadersUsed){ ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersUsed, table->InnerClipRect.Min.y + table_instance->LastTopHeadersRowHeight); } // Note: y1/y2 not always accurate
20411
0
            else if (rect_type == TRT_ColumnsContentHeadersIdeal){ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersIdeal, table->InnerClipRect.Min.y + table_instance->LastTopHeadersRowHeight); }
20412
0
            else if (rect_type == TRT_ColumnsContentFrozen)     { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXFrozen, table->InnerClipRect.Min.y + table_instance->LastFrozenHeight); }
20413
0
            else if (rect_type == TRT_ColumnsContentUnfrozen)   { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y + table_instance->LastFrozenHeight, c->ContentMaxXUnfrozen, table->InnerClipRect.Max.y); }
20414
0
            IM_ASSERT(0);
20415
0
            return ImRect();
20416
0
        }
20417
20418
0
        static ImRect GetWindowRect(ImGuiWindow* window, int rect_type)
20419
0
        {
20420
0
            if (rect_type == WRT_OuterRect)                 { return window->Rect(); }
20421
0
            else if (rect_type == WRT_OuterRectClipped)     { return window->OuterRectClipped; }
20422
0
            else if (rect_type == WRT_InnerRect)            { return window->InnerRect; }
20423
0
            else if (rect_type == WRT_InnerClipRect)        { return window->InnerClipRect; }
20424
0
            else if (rect_type == WRT_WorkRect)             { return window->WorkRect; }
20425
0
            else if (rect_type == WRT_Content)              { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); }
20426
0
            else if (rect_type == WRT_ContentIdeal)         { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSizeIdeal); }
20427
0
            else if (rect_type == WRT_ContentRegionRect)    { return window->ContentRegionRect; }
20428
0
            IM_ASSERT(0);
20429
0
            return ImRect();
20430
0
        }
20431
0
    };
20432
20433
    // Tools
20434
0
    if (TreeNode("Tools"))
20435
0
    {
20436
        // Debug Break features
20437
        // The Item Picker tool is super useful to visually select an item and break into the call-stack of where it was submitted.
20438
0
        SeparatorTextEx(0, "Debug breaks", NULL, CalcTextSize("(?)").x + g.Style.SeparatorTextPadding.x);
20439
0
        SameLine();
20440
0
        MetricsHelpMarker("Will call the IM_DEBUG_BREAK() macro to break in debugger.\nWarning: If you don't have a debugger attached, this will probably crash.");
20441
0
        if (Checkbox("Show Item Picker", &g.DebugItemPickerActive) && g.DebugItemPickerActive)
20442
0
            DebugStartItemPicker();
20443
0
        Checkbox("Show \"Debug Break\" buttons in other sections (io.ConfigDebugIsDebuggerPresent)", &g.IO.ConfigDebugIsDebuggerPresent);
20444
20445
0
        SeparatorText("Visualize");
20446
20447
0
        Checkbox("Show Debug Log", &cfg->ShowDebugLog);
20448
0
        SameLine();
20449
0
        MetricsHelpMarker("You can also call ImGui::ShowDebugLogWindow() from your code.");
20450
20451
0
        Checkbox("Show ID Stack Tool", &cfg->ShowIDStackTool);
20452
0
        SameLine();
20453
0
        MetricsHelpMarker("You can also call ImGui::ShowIDStackToolWindow() from your code.");
20454
20455
0
        Checkbox("Show windows begin order", &cfg->ShowWindowsBeginOrder);
20456
0
        Checkbox("Show windows rectangles", &cfg->ShowWindowsRects);
20457
0
        SameLine();
20458
0
        SetNextItemWidth(GetFontSize() * 12);
20459
0
        cfg->ShowWindowsRects |= Combo("##show_windows_rect_type", &cfg->ShowWindowsRectsType, wrt_rects_names, WRT_Count, WRT_Count);
20460
0
        if (cfg->ShowWindowsRects && g.NavWindow != NULL)
20461
0
        {
20462
0
            BulletText("'%s':", g.NavWindow->Name);
20463
0
            Indent();
20464
0
            for (int rect_n = 0; rect_n < WRT_Count; rect_n++)
20465
0
            {
20466
0
                ImRect r = Funcs::GetWindowRect(g.NavWindow, rect_n);
20467
0
                Text("(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), wrt_rects_names[rect_n]);
20468
0
            }
20469
0
            Unindent();
20470
0
        }
20471
20472
0
        Checkbox("Show tables rectangles", &cfg->ShowTablesRects);
20473
0
        SameLine();
20474
0
        SetNextItemWidth(GetFontSize() * 12);
20475
0
        cfg->ShowTablesRects |= Combo("##show_table_rects_type", &cfg->ShowTablesRectsType, trt_rects_names, TRT_Count, TRT_Count);
20476
0
        if (cfg->ShowTablesRects && g.NavWindow != NULL)
20477
0
        {
20478
0
            for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
20479
0
            {
20480
0
                ImGuiTable* table = g.Tables.TryGetMapData(table_n);
20481
0
                if (table == NULL || table->LastFrameActive < g.FrameCount - 1 || (table->OuterWindow != g.NavWindow && table->InnerWindow != g.NavWindow))
20482
0
                    continue;
20483
20484
0
                BulletText("Table 0x%08X (%d columns, in '%s')", table->ID, table->ColumnsCount, table->OuterWindow->Name);
20485
0
                if (IsItemHovered())
20486
0
                    GetForegroundDrawList()->AddRect(table->OuterRect.Min - ImVec2(1, 1), table->OuterRect.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
20487
0
                Indent();
20488
0
                char buf[128];
20489
0
                for (int rect_n = 0; rect_n < TRT_Count; rect_n++)
20490
0
                {
20491
0
                    if (rect_n >= TRT_ColumnsRect)
20492
0
                    {
20493
0
                        if (rect_n != TRT_ColumnsRect && rect_n != TRT_ColumnsClipRect)
20494
0
                            continue;
20495
0
                        for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
20496
0
                        {
20497
0
                            ImRect r = Funcs::GetTableRect(table, rect_n, column_n);
20498
0
                            ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) Col %d %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), column_n, trt_rects_names[rect_n]);
20499
0
                            Selectable(buf);
20500
0
                            if (IsItemHovered())
20501
0
                                GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
20502
0
                        }
20503
0
                    }
20504
0
                    else
20505
0
                    {
20506
0
                        ImRect r = Funcs::GetTableRect(table, rect_n, -1);
20507
0
                        ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), trt_rects_names[rect_n]);
20508
0
                        Selectable(buf);
20509
0
                        if (IsItemHovered())
20510
0
                            GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
20511
0
                    }
20512
0
                }
20513
0
                Unindent();
20514
0
            }
20515
0
        }
20516
0
        Checkbox("Show groups rectangles", &g.DebugShowGroupRects); // Storing in context as this is used by group code and prefers to be in hot-data
20517
20518
0
        SeparatorText("Validate");
20519
20520
0
        Checkbox("Debug Begin/BeginChild return value", &io.ConfigDebugBeginReturnValueLoop);
20521
0
        SameLine();
20522
0
        MetricsHelpMarker("Some calls to Begin()/BeginChild() will return false.\n\nWill cycle through window depths then repeat. Windows should be flickering while running.");
20523
20524
0
        Checkbox("UTF-8 Encoding viewer", &cfg->ShowTextEncodingViewer);
20525
0
        SameLine();
20526
0
        MetricsHelpMarker("You can also call ImGui::DebugTextEncoding() from your code with a given string to test that your UTF-8 encoding settings are correct.");
20527
0
        if (cfg->ShowTextEncodingViewer)
20528
0
        {
20529
0
            static char buf[64] = "";
20530
0
            SetNextItemWidth(-FLT_MIN);
20531
0
            InputText("##DebugTextEncodingBuf", buf, IM_ARRAYSIZE(buf));
20532
0
            if (buf[0] != 0)
20533
0
                DebugTextEncoding(buf);
20534
0
        }
20535
20536
0
        TreePop();
20537
0
    }
20538
20539
    // Windows
20540
0
    if (TreeNode("Windows", "Windows (%d)", g.Windows.Size))
20541
0
    {
20542
        //SetNextItemOpen(true, ImGuiCond_Once);
20543
0
        DebugNodeWindowsList(&g.Windows, "By display order");
20544
0
        DebugNodeWindowsList(&g.WindowsFocusOrder, "By focus order (root windows)");
20545
0
        if (TreeNode("By submission order (begin stack)"))
20546
0
        {
20547
            // Here we display windows in their submitted order/hierarchy, however note that the Begin stack doesn't constitute a Parent<>Child relationship!
20548
0
            ImVector<ImGuiWindow*>& temp_buffer = g.WindowsTempSortBuffer;
20549
0
            temp_buffer.resize(0);
20550
0
            for (ImGuiWindow* window : g.Windows)
20551
0
                if (window->LastFrameActive + 1 >= g.FrameCount)
20552
0
                    temp_buffer.push_back(window);
20553
0
            struct Func { static int IMGUI_CDECL WindowComparerByBeginOrder(const void* lhs, const void* rhs) { return ((int)(*(const ImGuiWindow* const *)lhs)->BeginOrderWithinContext - (*(const ImGuiWindow* const*)rhs)->BeginOrderWithinContext); } };
20554
0
            ImQsort(temp_buffer.Data, (size_t)temp_buffer.Size, sizeof(ImGuiWindow*), Func::WindowComparerByBeginOrder);
20555
0
            DebugNodeWindowsListByBeginStackParent(temp_buffer.Data, temp_buffer.Size, NULL);
20556
0
            TreePop();
20557
0
        }
20558
20559
0
        TreePop();
20560
0
    }
20561
20562
    // DrawLists
20563
0
    int drawlist_count = 0;
20564
0
    for (ImGuiViewportP* viewport : g.Viewports)
20565
0
        drawlist_count += viewport->DrawDataP.CmdLists.Size;
20566
0
    if (TreeNode("DrawLists", "DrawLists (%d)", drawlist_count))
20567
0
    {
20568
0
        Checkbox("Show ImDrawCmd mesh when hovering", &cfg->ShowDrawCmdMesh);
20569
0
        Checkbox("Show ImDrawCmd bounding boxes when hovering", &cfg->ShowDrawCmdBoundingBoxes);
20570
0
        for (ImGuiViewportP* viewport : g.Viewports)
20571
0
        {
20572
0
            bool viewport_has_drawlist = false;
20573
0
            for (ImDrawList* draw_list : viewport->DrawDataP.CmdLists)
20574
0
            {
20575
0
                if (!viewport_has_drawlist)
20576
0
                    Text("Active DrawLists in Viewport #%d, ID: 0x%08X", viewport->Idx, viewport->ID);
20577
0
                viewport_has_drawlist = true;
20578
0
                DebugNodeDrawList(NULL, viewport, draw_list, "DrawList");
20579
0
            }
20580
0
        }
20581
0
        TreePop();
20582
0
    }
20583
20584
    // Viewports
20585
0
    if (TreeNode("Viewports", "Viewports (%d)", g.Viewports.Size))
20586
0
    {
20587
0
        cfg->HighlightMonitorIdx = -1;
20588
0
        bool open = TreeNode("Monitors", "Monitors (%d)", g.PlatformIO.Monitors.Size);
20589
0
        SameLine();
20590
0
        MetricsHelpMarker("Dear ImGui uses monitor data:\n- to query DPI settings on a per monitor basis\n- to position popup/tooltips so they don't straddle monitors.");
20591
0
        if (open)
20592
0
        {
20593
0
            for (int i = 0; i < g.PlatformIO.Monitors.Size; i++)
20594
0
            {
20595
0
                DebugNodePlatformMonitor(&g.PlatformIO.Monitors[i], "Monitor", i);
20596
0
                if (IsItemHovered())
20597
0
                    cfg->HighlightMonitorIdx = i;
20598
0
            }
20599
0
            DebugNodePlatformMonitor(&g.FallbackMonitor, "Fallback", 0);
20600
0
            TreePop();
20601
0
        }
20602
20603
0
        SetNextItemOpen(true, ImGuiCond_Once);
20604
0
        if (TreeNode("Windows Minimap"))
20605
0
        {
20606
0
            RenderViewportsThumbnails();
20607
0
            TreePop();
20608
0
        }
20609
0
        cfg->HighlightViewportID = 0;
20610
20611
0
        BulletText("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport ? g.MouseViewport->ID : 0, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
20612
0
        if (TreeNode("Inferred Z order (front-to-back)"))
20613
0
        {
20614
0
            static ImVector<ImGuiViewportP*> viewports;
20615
0
            viewports.resize(g.Viewports.Size);
20616
0
            memcpy(viewports.Data, g.Viewports.Data, g.Viewports.size_in_bytes());
20617
0
            if (viewports.Size > 1)
20618
0
                ImQsort(viewports.Data, viewports.Size, sizeof(ImGuiViewport*), ViewportComparerByLastFocusedStampCount);
20619
0
            for (ImGuiViewportP* viewport : viewports)
20620
0
            {
20621
0
                BulletText("Viewport #%d, ID: 0x%08X, LastFocused = %08d, PlatformFocused = %s, Window: \"%s\"",
20622
0
                    viewport->Idx, viewport->ID, viewport->LastFocusedStampCount,
20623
0
                    (g.PlatformIO.Platform_GetWindowFocus && viewport->PlatformWindowCreated) ? (g.PlatformIO.Platform_GetWindowFocus(viewport) ? "1" : "0") : "N/A",
20624
0
                    viewport->Window ? viewport->Window->Name : "N/A");
20625
0
                if (IsItemHovered())
20626
0
                    cfg->HighlightViewportID = viewport->ID;
20627
0
            }
20628
0
            TreePop();
20629
0
        }
20630
20631
0
        for (ImGuiViewportP* viewport : g.Viewports)
20632
0
            DebugNodeViewport(viewport);
20633
0
        TreePop();
20634
0
    }
20635
20636
    // Details for Popups
20637
0
    if (TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size))
20638
0
    {
20639
0
        for (const ImGuiPopupData& popup_data : g.OpenPopupStack)
20640
0
        {
20641
            // As it's difficult to interact with tree nodes while popups are open, we display everything inline.
20642
0
            ImGuiWindow* window = popup_data.Window;
20643
0
            BulletText("PopupID: %08x, Window: '%s' (%s%s), RestoreNavWindow '%s', ParentWindow '%s'",
20644
0
                popup_data.PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? "Child;" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? "Menu;" : "",
20645
0
                popup_data.RestoreNavWindow ? popup_data.RestoreNavWindow->Name : "NULL", window && window->ParentWindow ? window->ParentWindow->Name : "NULL");
20646
0
        }
20647
0
        TreePop();
20648
0
    }
20649
20650
    // Details for TabBars
20651
0
    if (TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.GetAliveCount()))
20652
0
    {
20653
0
        for (int n = 0; n < g.TabBars.GetMapSize(); n++)
20654
0
            if (ImGuiTabBar* tab_bar = g.TabBars.TryGetMapData(n))
20655
0
            {
20656
0
                PushID(tab_bar);
20657
0
                DebugNodeTabBar(tab_bar, "TabBar");
20658
0
                PopID();
20659
0
            }
20660
0
        TreePop();
20661
0
    }
20662
20663
    // Details for Tables
20664
0
    if (TreeNode("Tables", "Tables (%d)", g.Tables.GetAliveCount()))
20665
0
    {
20666
0
        for (int n = 0; n < g.Tables.GetMapSize(); n++)
20667
0
            if (ImGuiTable* table = g.Tables.TryGetMapData(n))
20668
0
                DebugNodeTable(table);
20669
0
        TreePop();
20670
0
    }
20671
20672
    // Details for Fonts
20673
0
    ImFontAtlas* atlas = g.IO.Fonts;
20674
0
    if (TreeNode("Fonts", "Fonts (%d)", atlas->Fonts.Size))
20675
0
    {
20676
0
        ShowFontAtlas(atlas);
20677
0
        TreePop();
20678
0
    }
20679
20680
    // Details for InputText
20681
0
    if (TreeNode("InputText"))
20682
0
    {
20683
0
        DebugNodeInputTextState(&g.InputTextState);
20684
0
        TreePop();
20685
0
    }
20686
20687
    // Details for TypingSelect
20688
0
    if (TreeNode("TypingSelect", "TypingSelect (%d)", g.TypingSelectState.SearchBuffer[0] != 0 ? 1 : 0))
20689
0
    {
20690
0
        DebugNodeTypingSelectState(&g.TypingSelectState);
20691
0
        TreePop();
20692
0
    }
20693
20694
    // Details for MultiSelect
20695
0
    if (TreeNode("MultiSelect", "MultiSelect (%d)", g.MultiSelectStorage.GetAliveCount()))
20696
0
    {
20697
0
        ImGuiBoxSelectState* bs = &g.BoxSelectState;
20698
0
        BulletText("BoxSelect ID=0x%08X, Starting = %d, Active %d", bs->ID, bs->IsStarting, bs->IsActive);
20699
0
        for (int n = 0; n < g.MultiSelectStorage.GetMapSize(); n++)
20700
0
            if (ImGuiMultiSelectState* state = g.MultiSelectStorage.TryGetMapData(n))
20701
0
                DebugNodeMultiSelectState(state);
20702
0
        TreePop();
20703
0
    }
20704
20705
    // Details for Docking
20706
0
#ifdef IMGUI_HAS_DOCK
20707
0
    if (TreeNode("Docking"))
20708
0
    {
20709
0
        static bool root_nodes_only = true;
20710
0
        ImGuiDockContext* dc = &g.DockContext;
20711
0
        Checkbox("List root nodes", &root_nodes_only);
20712
0
        Checkbox("Ctrl shows window dock info", &cfg->ShowDockingNodes);
20713
0
        if (SmallButton("Clear nodes")) { DockContextClearNodes(&g, 0, true); }
20714
0
        SameLine();
20715
0
        if (SmallButton("Rebuild all")) { dc->WantFullRebuild = true; }
20716
0
        for (int n = 0; n < dc->Nodes.Data.Size; n++)
20717
0
            if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
20718
0
                if (!root_nodes_only || node->IsRootNode())
20719
0
                    DebugNodeDockNode(node, "Node");
20720
0
        TreePop();
20721
0
    }
20722
0
#endif // #ifdef IMGUI_HAS_DOCK
20723
20724
    // Settings
20725
0
    if (TreeNode("Settings"))
20726
0
    {
20727
0
        if (SmallButton("Clear"))
20728
0
            ClearIniSettings();
20729
0
        SameLine();
20730
0
        if (SmallButton("Save to memory"))
20731
0
            SaveIniSettingsToMemory();
20732
0
        SameLine();
20733
0
        if (SmallButton("Save to disk"))
20734
0
            SaveIniSettingsToDisk(g.IO.IniFilename);
20735
0
        SameLine();
20736
0
        if (g.IO.IniFilename)
20737
0
            Text("\"%s\"", g.IO.IniFilename);
20738
0
        else
20739
0
            TextUnformatted("<NULL>");
20740
0
        Checkbox("io.ConfigDebugIniSettings", &io.ConfigDebugIniSettings);
20741
0
        Text("SettingsDirtyTimer %.2f", g.SettingsDirtyTimer);
20742
0
        if (TreeNode("SettingsHandlers", "Settings handlers: (%d)", g.SettingsHandlers.Size))
20743
0
        {
20744
0
            for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
20745
0
                BulletText("\"%s\"", handler.TypeName);
20746
0
            TreePop();
20747
0
        }
20748
0
        if (TreeNode("SettingsWindows", "Settings packed data: Windows: %d bytes", g.SettingsWindows.size()))
20749
0
        {
20750
0
            for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
20751
0
                DebugNodeWindowSettings(settings);
20752
0
            TreePop();
20753
0
        }
20754
20755
0
        if (TreeNode("SettingsTables", "Settings packed data: Tables: %d bytes", g.SettingsTables.size()))
20756
0
        {
20757
0
            for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
20758
0
                DebugNodeTableSettings(settings);
20759
0
            TreePop();
20760
0
        }
20761
20762
0
#ifdef IMGUI_HAS_DOCK
20763
0
        if (TreeNode("SettingsDocking", "Settings packed data: Docking"))
20764
0
        {
20765
0
            ImGuiDockContext* dc = &g.DockContext;
20766
0
            Text("In SettingsWindows:");
20767
0
            for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
20768
0
                if (settings->DockId != 0)
20769
0
                    BulletText("Window '%s' -> DockId %08X DockOrder=%d", settings->GetName(), settings->DockId, settings->DockOrder);
20770
0
            Text("In SettingsNodes:");
20771
0
            for (int n = 0; n < dc->NodesSettings.Size; n++)
20772
0
            {
20773
0
                ImGuiDockNodeSettings* settings = &dc->NodesSettings[n];
20774
0
                const char* selected_tab_name = NULL;
20775
0
                if (settings->SelectedTabId)
20776
0
                {
20777
0
                    if (ImGuiWindow* window = FindWindowByID(settings->SelectedTabId))
20778
0
                        selected_tab_name = window->Name;
20779
0
                    else if (ImGuiWindowSettings* window_settings = FindWindowSettingsByID(settings->SelectedTabId))
20780
0
                        selected_tab_name = window_settings->GetName();
20781
0
                }
20782
0
                BulletText("Node %08X, Parent %08X, SelectedTab %08X ('%s')", settings->ID, settings->ParentNodeId, settings->SelectedTabId, selected_tab_name ? selected_tab_name : settings->SelectedTabId ? "N/A" : "");
20783
0
            }
20784
0
            TreePop();
20785
0
        }
20786
0
#endif // #ifdef IMGUI_HAS_DOCK
20787
20788
0
        if (TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size()))
20789
0
        {
20790
0
            InputTextMultiline("##Ini", (char*)(void*)g.SettingsIniData.c_str(), g.SettingsIniData.Buf.Size, ImVec2(-FLT_MIN, GetTextLineHeight() * 20), ImGuiInputTextFlags_ReadOnly);
20791
0
            TreePop();
20792
0
        }
20793
0
        TreePop();
20794
0
    }
20795
20796
    // Settings
20797
0
    if (TreeNode("Memory allocations"))
20798
0
    {
20799
0
        ImGuiDebugAllocInfo* info = &g.DebugAllocInfo;
20800
0
        Text("%d current allocations", info->TotalAllocCount - info->TotalFreeCount);
20801
0
        if (SmallButton("GC now")) { g.GcCompactAll = true; }
20802
0
        Text("Recent frames with allocations:");
20803
0
        int buf_size = IM_ARRAYSIZE(info->LastEntriesBuf);
20804
0
        for (int n = buf_size - 1; n >= 0; n--)
20805
0
        {
20806
0
            ImGuiDebugAllocEntry* entry = &info->LastEntriesBuf[(info->LastEntriesIdx - n + buf_size) % buf_size];
20807
0
            BulletText("Frame %06d: %+3d ( %2d alloc, %2d free )", entry->FrameCount, entry->AllocCount - entry->FreeCount, entry->AllocCount, entry->FreeCount);
20808
0
            if (n == 0)
20809
0
            {
20810
0
                SameLine();
20811
0
                Text("<- %d frames ago", g.FrameCount - entry->FrameCount);
20812
0
            }
20813
0
        }
20814
0
        TreePop();
20815
0
    }
20816
20817
0
    if (TreeNode("Inputs"))
20818
0
    {
20819
0
        Text("KEYBOARD/GAMEPAD/MOUSE KEYS");
20820
0
        {
20821
            // We iterate both legacy native range and named ImGuiKey ranges, which is a little odd but this allows displaying the data for old/new backends.
20822
            // User code should never have to go through such hoops! You can generally iterate between ImGuiKey_NamedKey_BEGIN and ImGuiKey_NamedKey_END.
20823
0
            Indent();
20824
0
#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
20825
0
            struct funcs { static bool IsLegacyNativeDupe(ImGuiKey) { return false; } };
20826
#else
20827
            struct funcs { static bool IsLegacyNativeDupe(ImGuiKey key) { return key >= 0 && key < 512 && GetIO().KeyMap[key] != -1; } }; // Hide Native<>ImGuiKey duplicates when both exists in the array
20828
            //Text("Legacy raw:");      for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key++) { if (io.KeysDown[key]) { SameLine(); Text("\"%s\" %d", GetKeyName(key), key); } }
20829
#endif
20830
0
            Text("Keys down:");         for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyDown(key)) continue;     SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); SameLine(); Text("(%.02f)", GetKeyData(key)->DownDuration); }
20831
0
            Text("Keys pressed:");      for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyPressed(key)) continue;  SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
20832
0
            Text("Keys released:");     for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyReleased(key)) continue; SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
20833
0
            Text("Keys mods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : "");
20834
0
            Text("Chars queue:");       for (int i = 0; i < io.InputQueueCharacters.Size; i++) { ImWchar c = io.InputQueueCharacters[i]; SameLine(); Text("\'%c\' (0x%04X)", (c > ' ' && c <= 255) ? (char)c : '?', c); } // FIXME: We should convert 'c' to UTF-8 here but the functions are not public.
20835
0
            DebugRenderKeyboardPreview(GetWindowDrawList());
20836
0
            Unindent();
20837
0
        }
20838
20839
0
        Text("MOUSE STATE");
20840
0
        {
20841
0
            Indent();
20842
0
            if (IsMousePosValid())
20843
0
                Text("Mouse pos: (%g, %g)", io.MousePos.x, io.MousePos.y);
20844
0
            else
20845
0
                Text("Mouse pos: <INVALID>");
20846
0
            Text("Mouse delta: (%g, %g)", io.MouseDelta.x, io.MouseDelta.y);
20847
0
            int count = IM_ARRAYSIZE(io.MouseDown);
20848
0
            Text("Mouse down:");     for (int i = 0; i < count; i++) if (IsMouseDown(i)) { SameLine(); Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]); }
20849
0
            Text("Mouse clicked:");  for (int i = 0; i < count; i++) if (IsMouseClicked(i)) { SameLine(); Text("b%d (%d)", i, io.MouseClickedCount[i]); }
20850
0
            Text("Mouse released:"); for (int i = 0; i < count; i++) if (IsMouseReleased(i)) { SameLine(); Text("b%d", i); }
20851
0
            Text("Mouse wheel: %.1f", io.MouseWheel);
20852
0
            Text("MouseStationaryTimer: %.2f", g.MouseStationaryTimer);
20853
0
            Text("Mouse source: %s", GetMouseSourceName(io.MouseSource));
20854
0
            Text("Pen Pressure: %.1f", io.PenPressure); // Note: currently unused
20855
0
            Unindent();
20856
0
        }
20857
20858
0
        Text("MOUSE WHEELING");
20859
0
        {
20860
0
            Indent();
20861
0
            Text("WheelingWindow: '%s'", g.WheelingWindow ? g.WheelingWindow->Name : "NULL");
20862
0
            Text("WheelingWindowReleaseTimer: %.2f", g.WheelingWindowReleaseTimer);
20863
0
            Text("WheelingAxisAvg[] = { %.3f, %.3f }, Main Axis: %s", g.WheelingAxisAvg.x, g.WheelingAxisAvg.y, (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? "X" : (g.WheelingAxisAvg.x < g.WheelingAxisAvg.y) ? "Y" : "<none>");
20864
0
            Unindent();
20865
0
        }
20866
20867
0
        Text("KEY OWNERS");
20868
0
        {
20869
0
            Indent();
20870
0
            if (BeginChild("##owners", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 8), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY, ImGuiWindowFlags_NoSavedSettings))
20871
0
                for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
20872
0
                {
20873
0
                    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
20874
0
                    if (owner_data->OwnerCurr == ImGuiKeyOwner_NoOwner)
20875
0
                        continue;
20876
0
                    Text("%s: 0x%08X%s", GetKeyName(key), owner_data->OwnerCurr,
20877
0
                        owner_data->LockUntilRelease ? " LockUntilRelease" : owner_data->LockThisFrame ? " LockThisFrame" : "");
20878
0
                    DebugLocateItemOnHover(owner_data->OwnerCurr);
20879
0
                }
20880
0
            EndChild();
20881
0
            Unindent();
20882
0
        }
20883
0
        Text("SHORTCUT ROUTING");
20884
0
        SameLine();
20885
0
        MetricsHelpMarker("Declared shortcut routes automatically set key owner when mods matches.");
20886
0
        {
20887
0
            Indent();
20888
0
            if (BeginChild("##routes", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 8), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY, ImGuiWindowFlags_NoSavedSettings))
20889
0
                for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
20890
0
                {
20891
0
                    ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
20892
0
                    for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; )
20893
0
                    {
20894
0
                        ImGuiKeyRoutingData* routing_data = &rt->Entries[idx];
20895
0
                        ImGuiKeyChord key_chord = key | routing_data->Mods;
20896
0
                        Text("%s: 0x%08X (scored %d)", GetKeyChordName(key_chord), routing_data->RoutingCurr, routing_data->RoutingCurrScore);
20897
0
                        DebugLocateItemOnHover(routing_data->RoutingCurr);
20898
0
                        if (g.IO.ConfigDebugIsDebuggerPresent)
20899
0
                        {
20900
0
                            SameLine();
20901
0
                            if (DebugBreakButton("**DebugBreak**", "in SetShortcutRouting() for this KeyChord"))
20902
0
                                g.DebugBreakInShortcutRouting = key_chord;
20903
0
                        }
20904
0
                        idx = routing_data->NextEntryIndex;
20905
0
                    }
20906
0
                }
20907
0
            EndChild();
20908
0
            Text("(ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: 0x%X)", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
20909
0
            Unindent();
20910
0
        }
20911
0
        TreePop();
20912
0
    }
20913
20914
0
    if (TreeNode("Internal state"))
20915
0
    {
20916
0
        Text("WINDOWING");
20917
0
        Indent();
20918
0
        Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
20919
0
        Text("HoveredWindow->Root: '%s'", g.HoveredWindow ? g.HoveredWindow->RootWindowDockTree->Name : "NULL");
20920
0
        Text("HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL");
20921
0
        Text("HoveredDockNode: 0x%08X", g.DebugHoveredDockNode ? g.DebugHoveredDockNode->ID : 0);
20922
0
        Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL");
20923
0
        Text("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport->ID, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
20924
0
        Unindent();
20925
20926
0
        Text("ITEMS");
20927
0
        Indent();
20928
0
        Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, GetInputSourceName(g.ActiveIdSource));
20929
0
        DebugLocateItemOnHover(g.ActiveId);
20930
0
        Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL");
20931
0
        Text("ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: %X", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
20932
0
        Text("HoveredId: 0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Not displaying g.HoveredId as it is update mid-frame
20933
0
        Text("HoverItemDelayId: 0x%08X, Timer: %.2f, ClearTimer: %.2f", g.HoverItemDelayId, g.HoverItemDelayTimer, g.HoverItemDelayClearTimer);
20934
0
        Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize);
20935
0
        DebugLocateItemOnHover(g.DragDropPayload.SourceId);
20936
0
        Unindent();
20937
20938
0
        Text("NAV,FOCUS");
20939
0
        Indent();
20940
0
        Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL");
20941
0
        Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer);
20942
0
        DebugLocateItemOnHover(g.NavId);
20943
0
        Text("NavInputSource: %s", GetInputSourceName(g.NavInputSource));
20944
0
        Text("NavLastValidSelectionUserData = %" IM_PRId64 " (0x%" IM_PRIX64 ")", g.NavLastValidSelectionUserData, g.NavLastValidSelectionUserData);
20945
0
        Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible);
20946
0
        Text("NavActivateId/DownId/PressedId: %08X/%08X/%08X", g.NavActivateId, g.NavActivateDownId, g.NavActivatePressedId);
20947
0
        Text("NavActivateFlags: %04X", g.NavActivateFlags);
20948
0
        Text("NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover);
20949
0
        Text("NavFocusScopeId = 0x%08X", g.NavFocusScopeId);
20950
0
        Text("NavFocusRoute[] = ");
20951
0
        for (int path_n = g.NavFocusRoute.Size - 1; path_n >= 0; path_n--)
20952
0
        {
20953
0
            const ImGuiFocusScopeData& focus_scope = g.NavFocusRoute[path_n];
20954
0
            SameLine(0.0f, 0.0f);
20955
0
            Text("0x%08X/", focus_scope.ID);
20956
0
            SetItemTooltip("In window \"%s\"", FindWindowByID(focus_scope.WindowID)->Name);
20957
0
        }
20958
0
        Text("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL");
20959
0
        Unindent();
20960
20961
0
        TreePop();
20962
0
    }
20963
20964
    // Overlay: Display windows Rectangles and Begin Order
20965
0
    if (cfg->ShowWindowsRects || cfg->ShowWindowsBeginOrder)
20966
0
    {
20967
0
        for (ImGuiWindow* window : g.Windows)
20968
0
        {
20969
0
            if (!window->WasActive)
20970
0
                continue;
20971
0
            ImDrawList* draw_list = GetForegroundDrawList(window);
20972
0
            if (cfg->ShowWindowsRects)
20973
0
            {
20974
0
                ImRect r = Funcs::GetWindowRect(window, cfg->ShowWindowsRectsType);
20975
0
                draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
20976
0
            }
20977
0
            if (cfg->ShowWindowsBeginOrder && !(window->Flags & ImGuiWindowFlags_ChildWindow))
20978
0
            {
20979
0
                char buf[32];
20980
0
                ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext);
20981
0
                float font_size = GetFontSize();
20982
0
                draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255));
20983
0
                draw_list->AddText(window->Pos, IM_COL32(255, 255, 255, 255), buf);
20984
0
            }
20985
0
        }
20986
0
    }
20987
20988
    // Overlay: Display Tables Rectangles
20989
0
    if (cfg->ShowTablesRects)
20990
0
    {
20991
0
        for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
20992
0
        {
20993
0
            ImGuiTable* table = g.Tables.TryGetMapData(table_n);
20994
0
            if (table == NULL || table->LastFrameActive < g.FrameCount - 1)
20995
0
                continue;
20996
0
            ImDrawList* draw_list = GetForegroundDrawList(table->OuterWindow);
20997
0
            if (cfg->ShowTablesRectsType >= TRT_ColumnsRect)
20998
0
            {
20999
0
                for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
21000
0
                {
21001
0
                    ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, column_n);
21002
0
                    ImU32 col = (table->HoveredColumnBody == column_n) ? IM_COL32(255, 255, 128, 255) : IM_COL32(255, 0, 128, 255);
21003
0
                    float thickness = (table->HoveredColumnBody == column_n) ? 3.0f : 1.0f;
21004
0
                    draw_list->AddRect(r.Min, r.Max, col, 0.0f, 0, thickness);
21005
0
                }
21006
0
            }
21007
0
            else
21008
0
            {
21009
0
                ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, -1);
21010
0
                draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
21011
0
            }
21012
0
        }
21013
0
    }
21014
21015
0
#ifdef IMGUI_HAS_DOCK
21016
    // Overlay: Display Docking info
21017
0
    if (cfg->ShowDockingNodes && g.IO.KeyCtrl && g.DebugHoveredDockNode)
21018
0
    {
21019
0
        char buf[64] = "";
21020
0
        char* p = buf;
21021
0
        ImGuiDockNode* node = g.DebugHoveredDockNode;
21022
0
        ImDrawList* overlay_draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
21023
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "DockId: %X%s\n", node->ID, node->IsCentralNode() ? " *CentralNode*" : "");
21024
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "WindowClass: %08X\n", node->WindowClass.ClassId);
21025
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "Size: (%.0f, %.0f)\n", node->Size.x, node->Size.y);
21026
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "SizeRef: (%.0f, %.0f)\n", node->SizeRef.x, node->SizeRef.y);
21027
0
        int depth = DockNodeGetDepth(node);
21028
0
        overlay_draw_list->AddRect(node->Pos + ImVec2(3, 3) * (float)depth, node->Pos + node->Size - ImVec2(3, 3) * (float)depth, IM_COL32(200, 100, 100, 255));
21029
0
        ImVec2 pos = node->Pos + ImVec2(3, 3) * (float)depth;
21030
0
        overlay_draw_list->AddRectFilled(pos - ImVec2(1, 1), pos + CalcTextSize(buf) + ImVec2(1, 1), IM_COL32(200, 100, 100, 255));
21031
0
        overlay_draw_list->AddText(NULL, 0.0f, pos, IM_COL32(255, 255, 255, 255), buf);
21032
0
    }
21033
0
#endif // #ifdef IMGUI_HAS_DOCK
21034
21035
0
    End();
21036
0
}
21037
21038
void ImGui::DebugBreakClearData()
21039
0
{
21040
    // Those fields are scattered in their respective subsystem to stay in hot-data locations
21041
0
    ImGuiContext& g = *GImGui;
21042
0
    g.DebugBreakInWindow = 0;
21043
0
    g.DebugBreakInTable = 0;
21044
0
    g.DebugBreakInShortcutRouting = ImGuiKey_None;
21045
0
}
21046
21047
void ImGui::DebugBreakButtonTooltip(bool keyboard_only, const char* description_of_location)
21048
0
{
21049
0
    if (!BeginItemTooltip())
21050
0
        return;
21051
0
    Text("To call IM_DEBUG_BREAK() %s:", description_of_location);
21052
0
    Separator();
21053
0
    TextUnformatted(keyboard_only ? "- Press 'Pause/Break' on keyboard." : "- Press 'Pause/Break' on keyboard.\n- or Click (may alter focus/active id).\n- or navigate using keyboard and press space.");
21054
0
    Separator();
21055
0
    TextUnformatted("Choose one way that doesn't interfere with what you are trying to debug!\nYou need a debugger attached or this will crash!");
21056
0
    EndTooltip();
21057
0
}
21058
21059
// Special button that doesn't take focus, doesn't take input owner, and can be activated without a click etc.
21060
// In order to reduce interferences with the contents we are trying to debug into.
21061
bool ImGui::DebugBreakButton(const char* label, const char* description_of_location)
21062
0
{
21063
0
    ImGuiWindow* window = GetCurrentWindow();
21064
0
    if (window->SkipItems)
21065
0
        return false;
21066
21067
0
    ImGuiContext& g = *GImGui;
21068
0
    const ImGuiID id = window->GetID(label);
21069
0
    const ImVec2 label_size = CalcTextSize(label, NULL, true);
21070
0
    ImVec2 pos = window->DC.CursorPos + ImVec2(0.0f, window->DC.CurrLineTextBaseOffset);
21071
0
    ImVec2 size = ImVec2(label_size.x + g.Style.FramePadding.x * 2.0f, label_size.y);
21072
21073
0
    const ImRect bb(pos, pos + size);
21074
0
    ItemSize(size, 0.0f);
21075
0
    if (!ItemAdd(bb, id))
21076
0
        return false;
21077
21078
    // WE DO NOT USE ButtonEx() or ButtonBehavior() in order to reduce our side-effects.
21079
0
    bool hovered = ItemHoverable(bb, id, g.CurrentItemFlags);
21080
0
    bool pressed = hovered && (IsKeyChordPressed(g.DebugBreakKeyChord) || IsMouseClicked(0) || g.NavActivateId == id);
21081
0
    DebugBreakButtonTooltip(false, description_of_location);
21082
21083
0
    ImVec4 col4f = GetStyleColorVec4(hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
21084
0
    ImVec4 hsv;
21085
0
    ColorConvertRGBtoHSV(col4f.x, col4f.y, col4f.z, hsv.x, hsv.y, hsv.z);
21086
0
    ColorConvertHSVtoRGB(hsv.x + 0.20f, hsv.y, hsv.z, col4f.x, col4f.y, col4f.z);
21087
21088
0
    RenderNavHighlight(bb, id);
21089
0
    RenderFrame(bb.Min, bb.Max, GetColorU32(col4f), true, g.Style.FrameRounding);
21090
0
    RenderTextClipped(bb.Min, bb.Max, label, NULL, &label_size, g.Style.ButtonTextAlign, &bb);
21091
21092
0
    IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags);
21093
0
    return pressed;
21094
0
}
21095
21096
// [DEBUG] Display contents of Columns
21097
void ImGui::DebugNodeColumns(ImGuiOldColumns* columns)
21098
0
{
21099
0
    if (!TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags))
21100
0
        return;
21101
0
    BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX);
21102
0
    for (ImGuiOldColumnData& column : columns->Columns)
21103
0
        BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", (int)columns->Columns.index_from_ptr(&column), column.OffsetNorm, GetColumnOffsetFromNorm(columns, column.OffsetNorm));
21104
0
    TreePop();
21105
0
}
21106
21107
static void DebugNodeDockNodeFlags(ImGuiDockNodeFlags* p_flags, const char* label, bool enabled)
21108
0
{
21109
0
    using namespace ImGui;
21110
0
    PushID(label);
21111
0
    PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0.0f, 0.0f));
21112
0
    Text("%s:", label);
21113
0
    if (!enabled)
21114
0
        BeginDisabled();
21115
0
    CheckboxFlags("NoResize", p_flags, ImGuiDockNodeFlags_NoResize);
21116
0
    CheckboxFlags("NoResizeX", p_flags, ImGuiDockNodeFlags_NoResizeX);
21117
0
    CheckboxFlags("NoResizeY",p_flags, ImGuiDockNodeFlags_NoResizeY);
21118
0
    CheckboxFlags("NoTabBar", p_flags, ImGuiDockNodeFlags_NoTabBar);
21119
0
    CheckboxFlags("HiddenTabBar", p_flags, ImGuiDockNodeFlags_HiddenTabBar);
21120
0
    CheckboxFlags("NoWindowMenuButton", p_flags, ImGuiDockNodeFlags_NoWindowMenuButton);
21121
0
    CheckboxFlags("NoCloseButton", p_flags, ImGuiDockNodeFlags_NoCloseButton);
21122
0
    CheckboxFlags("DockedWindowsInFocusRoute", p_flags, ImGuiDockNodeFlags_DockedWindowsInFocusRoute);
21123
0
    CheckboxFlags("NoDocking", p_flags, ImGuiDockNodeFlags_NoDocking); // Multiple flags
21124
0
    CheckboxFlags("NoDockingSplit", p_flags, ImGuiDockNodeFlags_NoDockingSplit);
21125
0
    CheckboxFlags("NoDockingSplitOther", p_flags, ImGuiDockNodeFlags_NoDockingSplitOther);
21126
0
    CheckboxFlags("NoDockingOver", p_flags, ImGuiDockNodeFlags_NoDockingOverMe);
21127
0
    CheckboxFlags("NoDockingOverOther", p_flags, ImGuiDockNodeFlags_NoDockingOverOther);
21128
0
    CheckboxFlags("NoDockingOverEmpty", p_flags, ImGuiDockNodeFlags_NoDockingOverEmpty);
21129
0
    CheckboxFlags("NoUndocking", p_flags, ImGuiDockNodeFlags_NoUndocking);
21130
0
    if (!enabled)
21131
0
        EndDisabled();
21132
0
    PopStyleVar();
21133
0
    PopID();
21134
0
}
21135
21136
// [DEBUG] Display contents of ImDockNode
21137
void ImGui::DebugNodeDockNode(ImGuiDockNode* node, const char* label)
21138
0
{
21139
0
    ImGuiContext& g = *GImGui;
21140
0
    const bool is_alive = (g.FrameCount - node->LastFrameAlive < 2);    // Submitted with ImGuiDockNodeFlags_KeepAliveOnly
21141
0
    const bool is_active = (g.FrameCount - node->LastFrameActive < 2);  // Submitted
21142
0
    if (!is_alive) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
21143
0
    bool open;
21144
0
    ImGuiTreeNodeFlags tree_node_flags = node->IsFocused ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
21145
0
    if (node->Windows.Size > 0)
21146
0
        open = TreeNodeEx((void*)(intptr_t)node->ID, tree_node_flags, "%s 0x%04X%s: %d windows (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", node->Windows.Size, node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
21147
0
    else
21148
0
        open = TreeNodeEx((void*)(intptr_t)node->ID, tree_node_flags, "%s 0x%04X%s: %s (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", (node->SplitAxis == ImGuiAxis_X) ? "horizontal split" : (node->SplitAxis == ImGuiAxis_Y) ? "vertical split" : "empty", node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
21149
0
    if (!is_alive) { PopStyleColor(); }
21150
0
    if (is_active && IsItemHovered())
21151
0
        if (ImGuiWindow* window = node->HostWindow ? node->HostWindow : node->VisibleWindow)
21152
0
            GetForegroundDrawList(window)->AddRect(node->Pos, node->Pos + node->Size, IM_COL32(255, 255, 0, 255));
21153
0
    if (open)
21154
0
    {
21155
0
        IM_ASSERT(node->ChildNodes[0] == NULL || node->ChildNodes[0]->ParentNode == node);
21156
0
        IM_ASSERT(node->ChildNodes[1] == NULL || node->ChildNodes[1]->ParentNode == node);
21157
0
        BulletText("Pos (%.0f,%.0f), Size (%.0f, %.0f) Ref (%.0f, %.0f)",
21158
0
            node->Pos.x, node->Pos.y, node->Size.x, node->Size.y, node->SizeRef.x, node->SizeRef.y);
21159
0
        DebugNodeWindow(node->HostWindow, "HostWindow");
21160
0
        DebugNodeWindow(node->VisibleWindow, "VisibleWindow");
21161
0
        BulletText("SelectedTabID: 0x%08X, LastFocusedNodeID: 0x%08X", node->SelectedTabId, node->LastFocusedNodeId);
21162
0
        BulletText("Misc:%s%s%s%s%s%s%s",
21163
0
            node->IsDockSpace() ? " IsDockSpace" : "",
21164
0
            node->IsCentralNode() ? " IsCentralNode" : "",
21165
0
            is_alive ? " IsAlive" : "", is_active ? " IsActive" : "", node->IsFocused ? " IsFocused" : "",
21166
0
            node->WantLockSizeOnce ? " WantLockSizeOnce" : "",
21167
0
            node->HasCentralNodeChild ? " HasCentralNodeChild" : "");
21168
0
        if (TreeNode("flags", "Flags Merged: 0x%04X, Local: 0x%04X, InWindows: 0x%04X, Shared: 0x%04X", node->MergedFlags, node->LocalFlags, node->LocalFlagsInWindows, node->SharedFlags))
21169
0
        {
21170
0
            if (BeginTable("flags", 4))
21171
0
            {
21172
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->MergedFlags, "MergedFlags", false);
21173
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->LocalFlags, "LocalFlags", true);
21174
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->LocalFlagsInWindows, "LocalFlagsInWindows", false);
21175
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->SharedFlags, "SharedFlags", true);
21176
0
                EndTable();
21177
0
            }
21178
0
            TreePop();
21179
0
        }
21180
0
        if (node->ParentNode)
21181
0
            DebugNodeDockNode(node->ParentNode, "ParentNode");
21182
0
        if (node->ChildNodes[0])
21183
0
            DebugNodeDockNode(node->ChildNodes[0], "Child[0]");
21184
0
        if (node->ChildNodes[1])
21185
0
            DebugNodeDockNode(node->ChildNodes[1], "Child[1]");
21186
0
        if (node->TabBar)
21187
0
            DebugNodeTabBar(node->TabBar, "TabBar");
21188
0
        DebugNodeWindowsList(&node->Windows, "Windows");
21189
21190
0
        TreePop();
21191
0
    }
21192
0
}
21193
21194
static void FormatTextureIDForDebugDisplay(char* buf, int buf_size, ImTextureID tex_id)
21195
0
{
21196
0
    union { void* ptr; int integer; } tex_id_opaque;
21197
0
    memcpy(&tex_id_opaque, &tex_id, ImMin(sizeof(void*), sizeof(tex_id)));
21198
0
    if (sizeof(tex_id) >= sizeof(void*))
21199
0
        ImFormatString(buf, buf_size, "0x%p", tex_id_opaque.ptr);
21200
0
    else
21201
0
        ImFormatString(buf, buf_size, "0x%04X", tex_id_opaque.integer);
21202
0
}
21203
21204
// [DEBUG] Display contents of ImDrawList
21205
// Note that both 'window' and 'viewport' may be NULL here. Viewport is generally null of destroyed popups which previously owned a viewport.
21206
void ImGui::DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, const ImDrawList* draw_list, const char* label)
21207
0
{
21208
0
    ImGuiContext& g = *GImGui;
21209
0
    ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
21210
0
    int cmd_count = draw_list->CmdBuffer.Size;
21211
0
    if (cmd_count > 0 && draw_list->CmdBuffer.back().ElemCount == 0 && draw_list->CmdBuffer.back().UserCallback == NULL)
21212
0
        cmd_count--;
21213
0
    bool node_open = TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, cmd_count);
21214
0
    if (draw_list == GetWindowDrawList())
21215
0
    {
21216
0
        SameLine();
21217
0
        TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered)
21218
0
        if (node_open)
21219
0
            TreePop();
21220
0
        return;
21221
0
    }
21222
21223
0
    ImDrawList* fg_draw_list = viewport ? GetForegroundDrawList(viewport) : NULL; // Render additional visuals into the top-most draw list
21224
0
    if (window && IsItemHovered() && fg_draw_list)
21225
0
        fg_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
21226
0
    if (!node_open)
21227
0
        return;
21228
21229
0
    if (window && !window->WasActive)
21230
0
        TextDisabled("Warning: owning Window is inactive. This DrawList is not being rendered!");
21231
21232
0
    for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.Data; pcmd < draw_list->CmdBuffer.Data + cmd_count; pcmd++)
21233
0
    {
21234
0
        if (pcmd->UserCallback)
21235
0
        {
21236
0
            BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
21237
0
            continue;
21238
0
        }
21239
21240
0
        char texid_desc[20];
21241
0
        FormatTextureIDForDebugDisplay(texid_desc, IM_ARRAYSIZE(texid_desc), pcmd->TextureId);
21242
0
        char buf[300];
21243
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d tris, Tex %s, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)",
21244
0
            pcmd->ElemCount / 3, texid_desc, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
21245
0
        bool pcmd_node_open = TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf);
21246
0
        if (IsItemHovered() && (cfg->ShowDrawCmdMesh || cfg->ShowDrawCmdBoundingBoxes) && fg_draw_list)
21247
0
            DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, cfg->ShowDrawCmdMesh, cfg->ShowDrawCmdBoundingBoxes);
21248
0
        if (!pcmd_node_open)
21249
0
            continue;
21250
21251
        // Calculate approximate coverage area (touched pixel count)
21252
        // This will be in pixels squared as long there's no post-scaling happening to the renderer output.
21253
0
        const ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
21254
0
        const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + pcmd->VtxOffset;
21255
0
        float total_area = 0.0f;
21256
0
        for (unsigned int idx_n = pcmd->IdxOffset; idx_n < pcmd->IdxOffset + pcmd->ElemCount; )
21257
0
        {
21258
0
            ImVec2 triangle[3];
21259
0
            for (int n = 0; n < 3; n++, idx_n++)
21260
0
                triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos;
21261
0
            total_area += ImTriangleArea(triangle[0], triangle[1], triangle[2]);
21262
0
        }
21263
21264
        // Display vertex information summary. Hover to get all triangles drawn in wire-frame
21265
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "Mesh: ElemCount: %d, VtxOffset: +%d, IdxOffset: +%d, Area: ~%0.f px", pcmd->ElemCount, pcmd->VtxOffset, pcmd->IdxOffset, total_area);
21266
0
        Selectable(buf);
21267
0
        if (IsItemHovered() && fg_draw_list)
21268
0
            DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, true, false);
21269
21270
        // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted.
21271
0
        ImGuiListClipper clipper;
21272
0
        clipper.Begin(pcmd->ElemCount / 3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible.
21273
0
        while (clipper.Step())
21274
0
            for (int prim = clipper.DisplayStart, idx_i = pcmd->IdxOffset + clipper.DisplayStart * 3; prim < clipper.DisplayEnd; prim++)
21275
0
            {
21276
0
                char* buf_p = buf, * buf_end = buf + IM_ARRAYSIZE(buf);
21277
0
                ImVec2 triangle[3];
21278
0
                for (int n = 0; n < 3; n++, idx_i++)
21279
0
                {
21280
0
                    const ImDrawVert& v = vtx_buffer[idx_buffer ? idx_buffer[idx_i] : idx_i];
21281
0
                    triangle[n] = v.pos;
21282
0
                    buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n",
21283
0
                        (n == 0) ? "Vert:" : "     ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
21284
0
                }
21285
21286
0
                Selectable(buf, false);
21287
0
                if (fg_draw_list && IsItemHovered())
21288
0
                {
21289
0
                    ImDrawListFlags backup_flags = fg_draw_list->Flags;
21290
0
                    fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
21291
0
                    fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f);
21292
0
                    fg_draw_list->Flags = backup_flags;
21293
0
                }
21294
0
            }
21295
0
        TreePop();
21296
0
    }
21297
0
    TreePop();
21298
0
}
21299
21300
// [DEBUG] Display mesh/aabb of a ImDrawCmd
21301
void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb)
21302
0
{
21303
0
    IM_ASSERT(show_mesh || show_aabb);
21304
21305
    // Draw wire-frame version of all triangles
21306
0
    ImRect clip_rect = draw_cmd->ClipRect;
21307
0
    ImRect vtxs_rect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
21308
0
    ImDrawListFlags backup_flags = out_draw_list->Flags;
21309
0
    out_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
21310
0
    for (unsigned int idx_n = draw_cmd->IdxOffset, idx_end = draw_cmd->IdxOffset + draw_cmd->ElemCount; idx_n < idx_end; )
21311
0
    {
21312
0
        ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; // We don't hold on those pointers past iterations as ->AddPolyline() may invalidate them if out_draw_list==draw_list
21313
0
        ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + draw_cmd->VtxOffset;
21314
21315
0
        ImVec2 triangle[3];
21316
0
        for (int n = 0; n < 3; n++, idx_n++)
21317
0
            vtxs_rect.Add((triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos));
21318
0
        if (show_mesh)
21319
0
            out_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f); // In yellow: mesh triangles
21320
0
    }
21321
    // Draw bounding boxes
21322
0
    if (show_aabb)
21323
0
    {
21324
0
        out_draw_list->AddRect(ImTrunc(clip_rect.Min), ImTrunc(clip_rect.Max), IM_COL32(255, 0, 255, 255)); // In pink: clipping rectangle submitted to GPU
21325
0
        out_draw_list->AddRect(ImTrunc(vtxs_rect.Min), ImTrunc(vtxs_rect.Max), IM_COL32(0, 255, 255, 255)); // In cyan: bounding box of triangles
21326
0
    }
21327
0
    out_draw_list->Flags = backup_flags;
21328
0
}
21329
21330
// [DEBUG] Display details for a single font, called by ShowStyleEditor().
21331
void ImGui::DebugNodeFont(ImFont* font)
21332
0
{
21333
0
    bool opened = TreeNode(font, "Font: \"%s\"\n%.2f px, %d glyphs, %d file(s)",
21334
0
        font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size, font->ConfigDataCount);
21335
0
    SameLine();
21336
0
    if (SmallButton("Set as default"))
21337
0
        GetIO().FontDefault = font;
21338
0
    if (!opened)
21339
0
        return;
21340
21341
    // Display preview text
21342
0
    PushFont(font);
21343
0
    Text("The quick brown fox jumps over the lazy dog");
21344
0
    PopFont();
21345
21346
    // Display details
21347
0
    SetNextItemWidth(GetFontSize() * 8);
21348
0
    DragFloat("Font scale", &font->Scale, 0.005f, 0.3f, 2.0f, "%.1f");
21349
0
    SameLine(); MetricsHelpMarker(
21350
0
        "Note that the default embedded font is NOT meant to be scaled.\n\n"
21351
0
        "Font are currently rendered into bitmaps at a given size at the time of building the atlas. "
21352
0
        "You may oversample them to get some flexibility with scaling. "
21353
0
        "You can also render at multiple sizes and select which one to use at runtime.\n\n"
21354
0
        "(Glimmer of hope: the atlas system will be rewritten in the future to make scaling more flexible.)");
21355
0
    Text("Ascent: %f, Descent: %f, Height: %f", font->Ascent, font->Descent, font->Ascent - font->Descent);
21356
0
    char c_str[5];
21357
0
    Text("Fallback character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->FallbackChar), font->FallbackChar);
21358
0
    Text("Ellipsis character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->EllipsisChar), font->EllipsisChar);
21359
0
    const int surface_sqrt = (int)ImSqrt((float)font->MetricsTotalSurface);
21360
0
    Text("Texture Area: about %d px ~%dx%d px", font->MetricsTotalSurface, surface_sqrt, surface_sqrt);
21361
0
    for (int config_i = 0; config_i < font->ConfigDataCount; config_i++)
21362
0
        if (font->ConfigData)
21363
0
            if (const ImFontConfig* cfg = &font->ConfigData[config_i])
21364
0
                BulletText("Input %d: \'%s\', Oversample: (%d,%d), PixelSnapH: %d, Offset: (%.1f,%.1f)",
21365
0
                    config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH, cfg->GlyphOffset.x, cfg->GlyphOffset.y);
21366
21367
    // Display all glyphs of the fonts in separate pages of 256 characters
21368
0
    if (TreeNode("Glyphs", "Glyphs (%d)", font->Glyphs.Size))
21369
0
    {
21370
0
        ImDrawList* draw_list = GetWindowDrawList();
21371
0
        const ImU32 glyph_col = GetColorU32(ImGuiCol_Text);
21372
0
        const float cell_size = font->FontSize * 1;
21373
0
        const float cell_spacing = GetStyle().ItemSpacing.y;
21374
0
        for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base += 256)
21375
0
        {
21376
            // Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k)
21377
            // This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT
21378
            // is large // (if ImWchar==ImWchar32 we will do at least about 272 queries here)
21379
0
            if (!(base & 4095) && font->IsGlyphRangeUnused(base, base + 4095))
21380
0
            {
21381
0
                base += 4096 - 256;
21382
0
                continue;
21383
0
            }
21384
21385
0
            int count = 0;
21386
0
            for (unsigned int n = 0; n < 256; n++)
21387
0
                if (font->FindGlyphNoFallback((ImWchar)(base + n)))
21388
0
                    count++;
21389
0
            if (count <= 0)
21390
0
                continue;
21391
0
            if (!TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph"))
21392
0
                continue;
21393
21394
            // Draw a 16x16 grid of glyphs
21395
0
            ImVec2 base_pos = GetCursorScreenPos();
21396
0
            for (unsigned int n = 0; n < 256; n++)
21397
0
            {
21398
                // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions
21399
                // available here and thus cannot easily generate a zero-terminated UTF-8 encoded string.
21400
0
                ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing));
21401
0
                ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size);
21402
0
                const ImFontGlyph* glyph = font->FindGlyphNoFallback((ImWchar)(base + n));
21403
0
                draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255, 255, 255, 100) : IM_COL32(255, 255, 255, 50));
21404
0
                if (!glyph)
21405
0
                    continue;
21406
0
                font->RenderChar(draw_list, cell_size, cell_p1, glyph_col, (ImWchar)(base + n));
21407
0
                if (IsMouseHoveringRect(cell_p1, cell_p2) && BeginTooltip())
21408
0
                {
21409
0
                    DebugNodeFontGlyph(font, glyph);
21410
0
                    EndTooltip();
21411
0
                }
21412
0
            }
21413
0
            Dummy(ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16));
21414
0
            TreePop();
21415
0
        }
21416
0
        TreePop();
21417
0
    }
21418
0
    TreePop();
21419
0
}
21420
21421
void ImGui::DebugNodeFontGlyph(ImFont*, const ImFontGlyph* glyph)
21422
0
{
21423
0
    Text("Codepoint: U+%04X", glyph->Codepoint);
21424
0
    Separator();
21425
0
    Text("Visible: %d", glyph->Visible);
21426
0
    Text("AdvanceX: %.1f", glyph->AdvanceX);
21427
0
    Text("Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1);
21428
0
    Text("UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1);
21429
0
}
21430
21431
// [DEBUG] Display contents of ImGuiStorage
21432
void ImGui::DebugNodeStorage(ImGuiStorage* storage, const char* label)
21433
0
{
21434
0
    if (!TreeNode(label, "%s: %d entries, %d bytes", label, storage->Data.Size, storage->Data.size_in_bytes()))
21435
0
        return;
21436
0
    for (const ImGuiStoragePair& p : storage->Data)
21437
0
    {
21438
0
        BulletText("Key 0x%08X Value { i: %d }", p.key, p.val_i); // Important: we currently don't store a type, real value may not be integer.
21439
0
        DebugLocateItemOnHover(p.key);
21440
0
    }
21441
0
    TreePop();
21442
0
}
21443
21444
// [DEBUG] Display contents of ImGuiTabBar
21445
void ImGui::DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label)
21446
0
{
21447
    // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings.
21448
0
    char buf[256];
21449
0
    char* p = buf;
21450
0
    const char* buf_end = buf + IM_ARRAYSIZE(buf);
21451
0
    const bool is_active = (tab_bar->PrevFrameVisible >= GetFrameCount() - 2);
21452
0
    p += ImFormatString(p, buf_end - p, "%s 0x%08X (%d tabs)%s  {", label, tab_bar->ID, tab_bar->Tabs.Size, is_active ? "" : " *Inactive*");
21453
0
    for (int tab_n = 0; tab_n < ImMin(tab_bar->Tabs.Size, 3); tab_n++)
21454
0
    {
21455
0
        ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
21456
0
        p += ImFormatString(p, buf_end - p, "%s'%s'", tab_n > 0 ? ", " : "", TabBarGetTabName(tab_bar, tab));
21457
0
    }
21458
0
    p += ImFormatString(p, buf_end - p, (tab_bar->Tabs.Size > 3) ? " ... }" : " } ");
21459
0
    if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
21460
0
    bool open = TreeNode(label, "%s", buf);
21461
0
    if (!is_active) { PopStyleColor(); }
21462
0
    if (is_active && IsItemHovered())
21463
0
    {
21464
0
        ImDrawList* draw_list = GetForegroundDrawList();
21465
0
        draw_list->AddRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, IM_COL32(255, 255, 0, 255));
21466
0
        draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
21467
0
        draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
21468
0
    }
21469
0
    if (open)
21470
0
    {
21471
0
        for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
21472
0
        {
21473
0
            ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
21474
0
            PushID(tab);
21475
0
            if (SmallButton("<")) { TabBarQueueReorder(tab_bar, tab, -1); } SameLine(0, 2);
21476
0
            if (SmallButton(">")) { TabBarQueueReorder(tab_bar, tab, +1); } SameLine();
21477
0
            Text("%02d%c Tab 0x%08X '%s' Offset: %.2f, Width: %.2f/%.2f",
21478
0
                tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, TabBarGetTabName(tab_bar, tab), tab->Offset, tab->Width, tab->ContentWidth);
21479
0
            PopID();
21480
0
        }
21481
0
        TreePop();
21482
0
    }
21483
0
}
21484
21485
void ImGui::DebugNodeViewport(ImGuiViewportP* viewport)
21486
0
{
21487
0
    ImGuiContext& g = *GImGui;
21488
0
    SetNextItemOpen(true, ImGuiCond_Once);
21489
0
    bool open = TreeNode((void*)(intptr_t)viewport->ID, "Viewport #%d, ID: 0x%08X, Parent: 0x%08X, Window: \"%s\"", viewport->Idx, viewport->ID, viewport->ParentViewportId, viewport->Window ? viewport->Window->Name : "N/A");
21490
0
    if (IsItemHovered())
21491
0
        g.DebugMetricsConfig.HighlightViewportID = viewport->ID;
21492
0
    if (open)
21493
0
    {
21494
0
        ImGuiWindowFlags flags = viewport->Flags;
21495
0
        BulletText("Main Pos: (%.0f,%.0f), Size: (%.0f,%.0f)\nWorkArea Inset Left: %.0f Top: %.0f, Right: %.0f, Bottom: %.0f\nMonitor: %d, DpiScale: %.0f%%",
21496
0
            viewport->Pos.x, viewport->Pos.y, viewport->Size.x, viewport->Size.y,
21497
0
            viewport->WorkInsetMin.x, viewport->WorkInsetMin.y, viewport->WorkInsetMax.x, viewport->WorkInsetMax.y,
21498
0
            viewport->PlatformMonitor, viewport->DpiScale * 100.0f);
21499
0
        if (viewport->Idx > 0) { SameLine(); if (SmallButton("Reset Pos")) { viewport->Pos = ImVec2(200, 200); viewport->UpdateWorkRect(); if (viewport->Window) viewport->Window->Pos = viewport->Pos; } }
21500
0
        BulletText("Flags: 0x%04X =%s%s%s%s%s%s%s%s%s%s%s%s%s", viewport->Flags,
21501
            //(flags & ImGuiViewportFlags_IsPlatformWindow) ? " IsPlatformWindow" : "", // Omitting because it is the standard
21502
0
            (flags & ImGuiViewportFlags_IsPlatformMonitor) ? " IsPlatformMonitor" : "",
21503
0
            (flags & ImGuiViewportFlags_IsMinimized) ? " IsMinimized" : "",
21504
0
            (flags & ImGuiViewportFlags_IsFocused) ? " IsFocused" : "",
21505
0
            (flags & ImGuiViewportFlags_OwnedByApp) ? " OwnedByApp" : "",
21506
0
            (flags & ImGuiViewportFlags_NoDecoration) ? " NoDecoration" : "",
21507
0
            (flags & ImGuiViewportFlags_NoTaskBarIcon) ? " NoTaskBarIcon" : "",
21508
0
            (flags & ImGuiViewportFlags_NoFocusOnAppearing) ? " NoFocusOnAppearing" : "",
21509
0
            (flags & ImGuiViewportFlags_NoFocusOnClick) ? " NoFocusOnClick" : "",
21510
0
            (flags & ImGuiViewportFlags_NoInputs) ? " NoInputs" : "",
21511
0
            (flags & ImGuiViewportFlags_NoRendererClear) ? " NoRendererClear" : "",
21512
0
            (flags & ImGuiViewportFlags_NoAutoMerge) ? " NoAutoMerge" : "",
21513
0
            (flags & ImGuiViewportFlags_TopMost) ? " TopMost" : "",
21514
0
            (flags & ImGuiViewportFlags_CanHostOtherWindows) ? " CanHostOtherWindows" : "");
21515
0
        for (ImDrawList* draw_list : viewport->DrawDataP.CmdLists)
21516
0
            DebugNodeDrawList(NULL, viewport, draw_list, "DrawList");
21517
0
        TreePop();
21518
0
    }
21519
0
}
21520
21521
void ImGui::DebugNodePlatformMonitor(ImGuiPlatformMonitor* monitor, const char* label, int idx)
21522
0
{
21523
0
    BulletText("%s %d: DPI %.0f%%\n MainMin (%.0f,%.0f), MainMax (%.0f,%.0f), MainSize (%.0f,%.0f)\n WorkMin (%.0f,%.0f), WorkMax (%.0f,%.0f), WorkSize (%.0f,%.0f)",
21524
0
        label, idx, monitor->DpiScale * 100.0f,
21525
0
        monitor->MainPos.x, monitor->MainPos.y, monitor->MainPos.x + monitor->MainSize.x, monitor->MainPos.y + monitor->MainSize.y, monitor->MainSize.x, monitor->MainSize.y,
21526
0
        monitor->WorkPos.x, monitor->WorkPos.y, monitor->WorkPos.x + monitor->WorkSize.x, monitor->WorkPos.y + monitor->WorkSize.y, monitor->WorkSize.x, monitor->WorkSize.y);
21527
0
}
21528
21529
void ImGui::DebugNodeWindow(ImGuiWindow* window, const char* label)
21530
0
{
21531
0
    if (window == NULL)
21532
0
    {
21533
0
        BulletText("%s: NULL", label);
21534
0
        return;
21535
0
    }
21536
21537
0
    ImGuiContext& g = *GImGui;
21538
0
    const bool is_active = window->WasActive;
21539
0
    ImGuiTreeNodeFlags tree_node_flags = (window == g.NavWindow) ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
21540
0
    if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
21541
0
    const bool open = TreeNodeEx(label, tree_node_flags, "%s '%s'%s", label, window->Name, is_active ? "" : " *Inactive*");
21542
0
    if (!is_active) { PopStyleColor(); }
21543
0
    if (IsItemHovered() && is_active)
21544
0
        GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
21545
0
    if (!open)
21546
0
        return;
21547
21548
0
    if (window->MemoryCompacted)
21549
0
        TextDisabled("Note: some memory buffers have been compacted/freed.");
21550
21551
0
    if (g.IO.ConfigDebugIsDebuggerPresent && DebugBreakButton("**DebugBreak**", "in Begin()"))
21552
0
        g.DebugBreakInWindow = window->ID;
21553
21554
0
    ImGuiWindowFlags flags = window->Flags;
21555
0
    DebugNodeDrawList(window, window->Viewport, window->DrawList, "DrawList");
21556
0
    BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), ContentSize (%.1f,%.1f) Ideal (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->ContentSize.x, window->ContentSize.y, window->ContentSizeIdeal.x, window->ContentSizeIdeal.y);
21557
0
    BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags,
21558
0
        (flags & ImGuiWindowFlags_ChildWindow)  ? "Child " : "",      (flags & ImGuiWindowFlags_Tooltip)     ? "Tooltip "   : "",  (flags & ImGuiWindowFlags_Popup) ? "Popup " : "",
21559
0
        (flags & ImGuiWindowFlags_Modal)        ? "Modal " : "",      (flags & ImGuiWindowFlags_ChildMenu)   ? "ChildMenu " : "",  (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "",
21560
0
        (flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : "");
21561
0
    if (flags & ImGuiWindowFlags_ChildWindow)
21562
0
        BulletText("ChildFlags: 0x%08X (%s%s%s%s..)", window->ChildFlags,
21563
0
            (window->ChildFlags & ImGuiChildFlags_Border) ? "Border " : "",
21564
0
            (window->ChildFlags & ImGuiChildFlags_ResizeX) ? "ResizeX " : "",
21565
0
            (window->ChildFlags & ImGuiChildFlags_ResizeY) ? "ResizeY " : "",
21566
0
            (window->ChildFlags & ImGuiChildFlags_NavFlattened) ? "NavFlattened " : "");
21567
0
    BulletText("WindowClassId: 0x%08X", window->WindowClass.ClassId);
21568
0
    BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f) Scrollbar:%s%s", window->Scroll.x, window->ScrollMax.x, window->Scroll.y, window->ScrollMax.y, window->ScrollbarX ? "X" : "", window->ScrollbarY ? "Y" : "");
21569
0
    BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1);
21570
0
    BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems);
21571
0
    for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
21572
0
    {
21573
0
        ImRect r = window->NavRectRel[layer];
21574
0
        if (r.Min.x >= r.Max.y && r.Min.y >= r.Max.y)
21575
0
            BulletText("NavLastIds[%d]: 0x%08X", layer, window->NavLastIds[layer]);
21576
0
        else
21577
0
            BulletText("NavLastIds[%d]: 0x%08X at +(%.1f,%.1f)(%.1f,%.1f)", layer, window->NavLastIds[layer], r.Min.x, r.Min.y, r.Max.x, r.Max.y);
21578
0
        DebugLocateItemOnHover(window->NavLastIds[layer]);
21579
0
    }
21580
0
    const ImVec2* pr = window->NavPreferredScoringPosRel;
21581
0
    for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
21582
0
        BulletText("NavPreferredScoringPosRel[%d] = {%.1f,%.1f)", layer, (pr[layer].x == FLT_MAX ? -99999.0f : pr[layer].x), (pr[layer].y == FLT_MAX ? -99999.0f : pr[layer].y)); // Display as 99999.0f so it looks neater.
21583
0
    BulletText("NavLayersActiveMask: %X, NavLastChildNavWindow: %s", window->DC.NavLayersActiveMask, window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL");
21584
21585
0
    BulletText("Viewport: %d%s, ViewportId: 0x%08X, ViewportPos: (%.1f,%.1f)", window->Viewport ? window->Viewport->Idx : -1, window->ViewportOwned ? " (Owned)" : "", window->ViewportId, window->ViewportPos.x, window->ViewportPos.y);
21586
0
    BulletText("ViewportMonitor: %d", window->Viewport ? window->Viewport->PlatformMonitor : -1);
21587
0
    BulletText("DockId: 0x%04X, DockOrder: %d, Act: %d, Vis: %d", window->DockId, window->DockOrder, window->DockIsActive, window->DockTabIsVisible);
21588
0
    if (window->DockNode || window->DockNodeAsHost)
21589
0
        DebugNodeDockNode(window->DockNodeAsHost ? window->DockNodeAsHost : window->DockNode, window->DockNodeAsHost ? "DockNodeAsHost" : "DockNode");
21590
21591
0
    if (window->RootWindow != window)               { DebugNodeWindow(window->RootWindow, "RootWindow"); }
21592
0
    if (window->RootWindowDockTree != window->RootWindow) { DebugNodeWindow(window->RootWindowDockTree, "RootWindowDockTree"); }
21593
0
    if (window->ParentWindow != NULL)               { DebugNodeWindow(window->ParentWindow, "ParentWindow"); }
21594
0
    if (window->ParentWindowForFocusRoute != NULL)  { DebugNodeWindow(window->ParentWindowForFocusRoute, "ParentWindowForFocusRoute"); }
21595
0
    if (window->DC.ChildWindows.Size > 0)           { DebugNodeWindowsList(&window->DC.ChildWindows, "ChildWindows"); }
21596
0
    if (window->ColumnsStorage.Size > 0 && TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size))
21597
0
    {
21598
0
        for (ImGuiOldColumns& columns : window->ColumnsStorage)
21599
0
            DebugNodeColumns(&columns);
21600
0
        TreePop();
21601
0
    }
21602
0
    DebugNodeStorage(&window->StateStorage, "Storage");
21603
0
    TreePop();
21604
0
}
21605
21606
void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings* settings)
21607
0
{
21608
0
    if (settings->WantDelete)
21609
0
        BeginDisabled();
21610
0
    Text("0x%08X \"%s\" Pos (%d,%d) Size (%d,%d) Collapsed=%d",
21611
0
        settings->ID, settings->GetName(), settings->Pos.x, settings->Pos.y, settings->Size.x, settings->Size.y, settings->Collapsed);
21612
0
    if (settings->WantDelete)
21613
0
        EndDisabled();
21614
0
}
21615
21616
void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>* windows, const char* label)
21617
0
{
21618
0
    if (!TreeNode(label, "%s (%d)", label, windows->Size))
21619
0
        return;
21620
0
    for (int i = windows->Size - 1; i >= 0; i--) // Iterate front to back
21621
0
    {
21622
0
        PushID((*windows)[i]);
21623
0
        DebugNodeWindow((*windows)[i], "Window");
21624
0
        PopID();
21625
0
    }
21626
0
    TreePop();
21627
0
}
21628
21629
// FIXME-OPT: This is technically suboptimal, but it is simpler this way.
21630
void ImGui::DebugNodeWindowsListByBeginStackParent(ImGuiWindow** windows, int windows_size, ImGuiWindow* parent_in_begin_stack)
21631
0
{
21632
0
    for (int i = 0; i < windows_size; i++)
21633
0
    {
21634
0
        ImGuiWindow* window = windows[i];
21635
0
        if (window->ParentWindowInBeginStack != parent_in_begin_stack)
21636
0
            continue;
21637
0
        char buf[20];
21638
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "[%04d] Window", window->BeginOrderWithinContext);
21639
        //BulletText("[%04d] Window '%s'", window->BeginOrderWithinContext, window->Name);
21640
0
        DebugNodeWindow(window, buf);
21641
0
        Indent();
21642
0
        DebugNodeWindowsListByBeginStackParent(windows + i + 1, windows_size - i - 1, window);
21643
0
        Unindent();
21644
0
    }
21645
0
}
21646
21647
//-----------------------------------------------------------------------------
21648
// [SECTION] DEBUG LOG WINDOW
21649
//-----------------------------------------------------------------------------
21650
21651
void ImGui::DebugLog(const char* fmt, ...)
21652
0
{
21653
0
    va_list args;
21654
0
    va_start(args, fmt);
21655
0
    DebugLogV(fmt, args);
21656
0
    va_end(args);
21657
0
}
21658
21659
void ImGui::DebugLogV(const char* fmt, va_list args)
21660
0
{
21661
0
    ImGuiContext& g = *GImGui;
21662
0
    const int old_size = g.DebugLogBuf.size();
21663
0
    if (g.ContextName[0] != 0)
21664
0
        g.DebugLogBuf.appendf("[%s] [%05d] ", g.ContextName, g.FrameCount);
21665
0
    else
21666
0
        g.DebugLogBuf.appendf("[%05d] ", g.FrameCount);
21667
0
    g.DebugLogBuf.appendfv(fmt, args);
21668
0
    g.DebugLogIndex.append(g.DebugLogBuf.c_str(), old_size, g.DebugLogBuf.size());
21669
0
    if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTTY)
21670
0
        IMGUI_DEBUG_PRINTF("%s", g.DebugLogBuf.begin() + old_size);
21671
#ifdef IMGUI_ENABLE_TEST_ENGINE
21672
    // IMGUI_TEST_ENGINE_LOG() adds a trailing \n automatically
21673
    const int new_size = g.DebugLogBuf.size();
21674
    const bool trailing_carriage_return = (g.DebugLogBuf[new_size - 1] == '\n');
21675
    if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTestEngine)
21676
        IMGUI_TEST_ENGINE_LOG("%.*s", new_size - old_size - (trailing_carriage_return ? 1 : 0), g.DebugLogBuf.begin() + old_size);
21677
#endif
21678
0
}
21679
21680
// FIXME-LAYOUT: To be done automatically via layout mode once we rework ItemSize/ItemAdd into ItemLayout.
21681
static void SameLineOrWrap(const ImVec2& size)
21682
0
{
21683
0
    ImGuiContext& g = *GImGui;
21684
0
    ImGuiWindow* window = g.CurrentWindow;
21685
0
    ImVec2 pos(window->DC.CursorPosPrevLine.x + g.Style.ItemSpacing.x, window->DC.CursorPosPrevLine.y);
21686
0
    if (window->WorkRect.Contains(ImRect(pos, pos + size)))
21687
0
        ImGui::SameLine();
21688
0
}
21689
21690
static void ShowDebugLogFlag(const char* name, ImGuiDebugLogFlags flags)
21691
0
{
21692
0
    ImGuiContext& g = *GImGui;
21693
0
    ImVec2 size(ImGui::GetFrameHeight() + g.Style.ItemInnerSpacing.x + ImGui::CalcTextSize(name).x, ImGui::GetFrameHeight());
21694
0
    SameLineOrWrap(size); // FIXME-LAYOUT: To be done automatically once we rework ItemSize/ItemAdd into ItemLayout.
21695
0
    if (ImGui::CheckboxFlags(name, &g.DebugLogFlags, flags) && g.IO.KeyShift && (g.DebugLogFlags & flags) != 0)
21696
0
    {
21697
0
        g.DebugLogAutoDisableFrames = 2;
21698
0
        g.DebugLogAutoDisableFlags |= flags;
21699
0
    }
21700
0
    ImGui::SetItemTooltip("Hold SHIFT when clicking to enable for 2 frames only (useful for spammy log entries)");
21701
0
}
21702
21703
void ImGui::ShowDebugLogWindow(bool* p_open)
21704
0
{
21705
0
    ImGuiContext& g = *GImGui;
21706
0
    if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize))
21707
0
        SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 12.0f), ImGuiCond_FirstUseEver);
21708
0
    if (!Begin("Dear ImGui Debug Log", p_open) || GetCurrentWindow()->BeginCount > 1)
21709
0
    {
21710
0
        End();
21711
0
        return;
21712
0
    }
21713
21714
0
    ImGuiDebugLogFlags all_enable_flags = ImGuiDebugLogFlags_EventMask_ & ~ImGuiDebugLogFlags_EventInputRouting;
21715
0
    CheckboxFlags("All", &g.DebugLogFlags, all_enable_flags);
21716
0
    SetItemTooltip("(except InputRouting which is spammy)");
21717
21718
0
    ShowDebugLogFlag("ActiveId", ImGuiDebugLogFlags_EventActiveId);
21719
0
    ShowDebugLogFlag("Clipper", ImGuiDebugLogFlags_EventClipper);
21720
0
    ShowDebugLogFlag("Docking", ImGuiDebugLogFlags_EventDocking);
21721
0
    ShowDebugLogFlag("Focus", ImGuiDebugLogFlags_EventFocus);
21722
0
    ShowDebugLogFlag("IO", ImGuiDebugLogFlags_EventIO);
21723
0
    ShowDebugLogFlag("Nav", ImGuiDebugLogFlags_EventNav);
21724
0
    ShowDebugLogFlag("Popup", ImGuiDebugLogFlags_EventPopup);
21725
0
    ShowDebugLogFlag("Selection", ImGuiDebugLogFlags_EventSelection);
21726
0
    ShowDebugLogFlag("Viewport", ImGuiDebugLogFlags_EventViewport);
21727
0
    ShowDebugLogFlag("InputRouting", ImGuiDebugLogFlags_EventInputRouting);
21728
21729
0
    if (SmallButton("Clear"))
21730
0
    {
21731
0
        g.DebugLogBuf.clear();
21732
0
        g.DebugLogIndex.clear();
21733
0
    }
21734
0
    SameLine();
21735
0
    if (SmallButton("Copy"))
21736
0
        SetClipboardText(g.DebugLogBuf.c_str());
21737
0
    SameLine();
21738
0
    if (SmallButton("Configure Outputs.."))
21739
0
        OpenPopup("Outputs");
21740
0
    if (BeginPopup("Outputs"))
21741
0
    {
21742
0
        CheckboxFlags("OutputToTTY", &g.DebugLogFlags, ImGuiDebugLogFlags_OutputToTTY);
21743
0
#ifndef IMGUI_ENABLE_TEST_ENGINE
21744
0
        BeginDisabled();
21745
0
#endif
21746
0
        CheckboxFlags("OutputToTestEngine", &g.DebugLogFlags, ImGuiDebugLogFlags_OutputToTestEngine);
21747
0
#ifndef IMGUI_ENABLE_TEST_ENGINE
21748
0
        EndDisabled();
21749
0
#endif
21750
0
        EndPopup();
21751
0
    }
21752
21753
0
    BeginChild("##log", ImVec2(0.0f, 0.0f), ImGuiChildFlags_Border, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar);
21754
21755
0
    const ImGuiDebugLogFlags backup_log_flags = g.DebugLogFlags;
21756
0
    g.DebugLogFlags &= ~ImGuiDebugLogFlags_EventClipper;
21757
21758
0
    ImGuiListClipper clipper;
21759
0
    clipper.Begin(g.DebugLogIndex.size());
21760
0
    while (clipper.Step())
21761
0
        for (int line_no = clipper.DisplayStart; line_no < clipper.DisplayEnd; line_no++)
21762
0
            DebugTextUnformattedWithLocateItem(g.DebugLogIndex.get_line_begin(g.DebugLogBuf.c_str(), line_no), g.DebugLogIndex.get_line_end(g.DebugLogBuf.c_str(), line_no));
21763
0
    g.DebugLogFlags = backup_log_flags;
21764
0
    if (GetScrollY() >= GetScrollMaxY())
21765
0
        SetScrollHereY(1.0f);
21766
0
    EndChild();
21767
21768
0
    End();
21769
0
}
21770
21771
// Display line, search for 0xXXXXXXXX identifiers and call DebugLocateItemOnHover() when hovered.
21772
void ImGui::DebugTextUnformattedWithLocateItem(const char* line_begin, const char* line_end)
21773
0
{
21774
0
    TextUnformatted(line_begin, line_end);
21775
0
    if (!IsItemHovered())
21776
0
        return;
21777
0
    ImGuiContext& g = *GImGui;
21778
0
    ImRect text_rect = g.LastItemData.Rect;
21779
0
    for (const char* p = line_begin; p <= line_end - 10; p++)
21780
0
    {
21781
0
        ImGuiID id = 0;
21782
0
        if (p[0] != '0' || (p[1] != 'x' && p[1] != 'X') || sscanf(p + 2, "%X", &id) != 1 || ImCharIsXdigitA(p[10]))
21783
0
            continue;
21784
0
        ImVec2 p0 = CalcTextSize(line_begin, p);
21785
0
        ImVec2 p1 = CalcTextSize(p, p + 10);
21786
0
        g.LastItemData.Rect = ImRect(text_rect.Min + ImVec2(p0.x, 0.0f), text_rect.Min + ImVec2(p0.x + p1.x, p1.y));
21787
0
        if (IsMouseHoveringRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max, true))
21788
0
            DebugLocateItemOnHover(id);
21789
0
        p += 10;
21790
0
    }
21791
0
}
21792
21793
//-----------------------------------------------------------------------------
21794
// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, ID STACK TOOL)
21795
//-----------------------------------------------------------------------------
21796
21797
// Draw a small cross at current CursorPos in current window's DrawList
21798
void ImGui::DebugDrawCursorPos(ImU32 col)
21799
0
{
21800
0
    ImGuiContext& g = *GImGui;
21801
0
    ImGuiWindow* window = g.CurrentWindow;
21802
0
    ImVec2 pos = window->DC.CursorPos;
21803
0
    window->DrawList->AddLine(ImVec2(pos.x, pos.y - 3.0f), ImVec2(pos.x, pos.y + 4.0f), col, 1.0f);
21804
0
    window->DrawList->AddLine(ImVec2(pos.x - 3.0f, pos.y), ImVec2(pos.x + 4.0f, pos.y), col, 1.0f);
21805
0
}
21806
21807
// Draw a 10px wide rectangle around CurposPos.x using Line Y1/Y2 in current window's DrawList
21808
void ImGui::DebugDrawLineExtents(ImU32 col)
21809
0
{
21810
0
    ImGuiContext& g = *GImGui;
21811
0
    ImGuiWindow* window = g.CurrentWindow;
21812
0
    float curr_x = window->DC.CursorPos.x;
21813
0
    float line_y1 = (window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y);
21814
0
    float line_y2 = line_y1 + (window->DC.IsSameLine ? window->DC.PrevLineSize.y : window->DC.CurrLineSize.y);
21815
0
    window->DrawList->AddLine(ImVec2(curr_x - 5.0f, line_y1), ImVec2(curr_x + 5.0f, line_y1), col, 1.0f);
21816
0
    window->DrawList->AddLine(ImVec2(curr_x - 0.5f, line_y1), ImVec2(curr_x - 0.5f, line_y2), col, 1.0f);
21817
0
    window->DrawList->AddLine(ImVec2(curr_x - 5.0f, line_y2), ImVec2(curr_x + 5.0f, line_y2), col, 1.0f);
21818
0
}
21819
21820
// Draw last item rect in ForegroundDrawList (so it is always visible)
21821
void ImGui::DebugDrawItemRect(ImU32 col)
21822
0
{
21823
0
    ImGuiContext& g = *GImGui;
21824
0
    ImGuiWindow* window = g.CurrentWindow;
21825
0
    GetForegroundDrawList(window)->AddRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max, col);
21826
0
}
21827
21828
// [DEBUG] Locate item position/rectangle given an ID.
21829
static const ImU32 DEBUG_LOCATE_ITEM_COLOR = IM_COL32(0, 255, 0, 255);  // Green
21830
21831
void ImGui::DebugLocateItem(ImGuiID target_id)
21832
0
{
21833
0
    ImGuiContext& g = *GImGui;
21834
0
    g.DebugLocateId = target_id;
21835
0
    g.DebugLocateFrames = 2;
21836
0
    g.DebugBreakInLocateId = false;
21837
0
}
21838
21839
// FIXME: Doesn't work over through a modal window, because they clear HoveredWindow.
21840
void ImGui::DebugLocateItemOnHover(ImGuiID target_id)
21841
0
{
21842
0
    if (target_id == 0 || !IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenBlockedByPopup))
21843
0
        return;
21844
0
    ImGuiContext& g = *GImGui;
21845
0
    DebugLocateItem(target_id);
21846
0
    GetForegroundDrawList(g.CurrentWindow)->AddRect(g.LastItemData.Rect.Min - ImVec2(3.0f, 3.0f), g.LastItemData.Rect.Max + ImVec2(3.0f, 3.0f), DEBUG_LOCATE_ITEM_COLOR);
21847
21848
    // Can't easily use a context menu here because it will mess with focus, active id etc.
21849
0
    if (g.IO.ConfigDebugIsDebuggerPresent && g.MouseStationaryTimer > 1.0f)
21850
0
    {
21851
0
        DebugBreakButtonTooltip(false, "in ItemAdd()");
21852
0
        if (IsKeyChordPressed(g.DebugBreakKeyChord))
21853
0
            g.DebugBreakInLocateId = true;
21854
0
    }
21855
0
}
21856
21857
void ImGui::DebugLocateItemResolveWithLastItem()
21858
0
{
21859
0
    ImGuiContext& g = *GImGui;
21860
21861
    // [DEBUG] Debug break requested by user
21862
0
    if (g.DebugBreakInLocateId)
21863
0
        IM_DEBUG_BREAK();
21864
21865
0
    ImGuiLastItemData item_data = g.LastItemData;
21866
0
    g.DebugLocateId = 0;
21867
0
    ImDrawList* draw_list = GetForegroundDrawList(g.CurrentWindow);
21868
0
    ImRect r = item_data.Rect;
21869
0
    r.Expand(3.0f);
21870
0
    ImVec2 p1 = g.IO.MousePos;
21871
0
    ImVec2 p2 = ImVec2((p1.x < r.Min.x) ? r.Min.x : (p1.x > r.Max.x) ? r.Max.x : p1.x, (p1.y < r.Min.y) ? r.Min.y : (p1.y > r.Max.y) ? r.Max.y : p1.y);
21872
0
    draw_list->AddRect(r.Min, r.Max, DEBUG_LOCATE_ITEM_COLOR);
21873
0
    draw_list->AddLine(p1, p2, DEBUG_LOCATE_ITEM_COLOR);
21874
0
}
21875
21876
void ImGui::DebugStartItemPicker()
21877
0
{
21878
0
    ImGuiContext& g = *GImGui;
21879
0
    g.DebugItemPickerActive = true;
21880
0
}
21881
21882
// [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.
21883
void ImGui::UpdateDebugToolItemPicker()
21884
84.9k
{
21885
84.9k
    ImGuiContext& g = *GImGui;
21886
84.9k
    g.DebugItemPickerBreakId = 0;
21887
84.9k
    if (!g.DebugItemPickerActive)
21888
84.9k
        return;
21889
21890
0
    const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
21891
0
    SetMouseCursor(ImGuiMouseCursor_Hand);
21892
0
    if (IsKeyPressed(ImGuiKey_Escape))
21893
0
        g.DebugItemPickerActive = false;
21894
0
    const bool change_mapping = g.IO.KeyMods == (ImGuiMod_Ctrl | ImGuiMod_Shift);
21895
0
    if (!change_mapping && IsMouseClicked(g.DebugItemPickerMouseButton) && hovered_id)
21896
0
    {
21897
0
        g.DebugItemPickerBreakId = hovered_id;
21898
0
        g.DebugItemPickerActive = false;
21899
0
    }
21900
0
    for (int mouse_button = 0; mouse_button < 3; mouse_button++)
21901
0
        if (change_mapping && IsMouseClicked(mouse_button))
21902
0
            g.DebugItemPickerMouseButton = (ImU8)mouse_button;
21903
0
    SetNextWindowBgAlpha(0.70f);
21904
0
    if (!BeginTooltip())
21905
0
        return;
21906
0
    Text("HoveredId: 0x%08X", hovered_id);
21907
0
    Text("Press ESC to abort picking.");
21908
0
    const char* mouse_button_names[] = { "Left", "Right", "Middle" };
21909
0
    if (change_mapping)
21910
0
        Text("Remap w/ Ctrl+Shift: click anywhere to select new mouse button.");
21911
0
    else
21912
0
        TextColored(GetStyleColorVec4(hovered_id ? ImGuiCol_Text : ImGuiCol_TextDisabled), "Click %s Button to break in debugger! (remap w/ Ctrl+Shift)", mouse_button_names[g.DebugItemPickerMouseButton]);
21913
0
    EndTooltip();
21914
0
}
21915
21916
// [DEBUG] ID Stack Tool: update queries. Called by NewFrame()
21917
void ImGui::UpdateDebugToolStackQueries()
21918
84.9k
{
21919
84.9k
    ImGuiContext& g = *GImGui;
21920
84.9k
    ImGuiIDStackTool* tool = &g.DebugIDStackTool;
21921
21922
    // Clear hook when id stack tool is not visible
21923
84.9k
    g.DebugHookIdInfo = 0;
21924
84.9k
    if (g.FrameCount != tool->LastActiveFrame + 1)
21925
84.9k
        return;
21926
21927
    // Update queries. The steps are: -1: query Stack, >= 0: query each stack item
21928
    // We can only perform 1 ID Info query every frame. This is designed so the GetID() tests are cheap and constant-time
21929
6
    const ImGuiID query_id = g.HoveredIdPreviousFrame ? g.HoveredIdPreviousFrame : g.ActiveId;
21930
6
    if (tool->QueryId != query_id)
21931
0
    {
21932
0
        tool->QueryId = query_id;
21933
0
        tool->StackLevel = -1;
21934
0
        tool->Results.resize(0);
21935
0
    }
21936
6
    if (query_id == 0)
21937
6
        return;
21938
21939
    // Advance to next stack level when we got our result, or after 2 frames (in case we never get a result)
21940
0
    int stack_level = tool->StackLevel;
21941
0
    if (stack_level >= 0 && stack_level < tool->Results.Size)
21942
0
        if (tool->Results[stack_level].QuerySuccess || tool->Results[stack_level].QueryFrameCount > 2)
21943
0
            tool->StackLevel++;
21944
21945
    // Update hook
21946
0
    stack_level = tool->StackLevel;
21947
0
    if (stack_level == -1)
21948
0
        g.DebugHookIdInfo = query_id;
21949
0
    if (stack_level >= 0 && stack_level < tool->Results.Size)
21950
0
    {
21951
0
        g.DebugHookIdInfo = tool->Results[stack_level].ID;
21952
0
        tool->Results[stack_level].QueryFrameCount++;
21953
0
    }
21954
0
}
21955
21956
// [DEBUG] ID Stack tool: hooks called by GetID() family functions
21957
void ImGui::DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void* data_id, const void* data_id_end)
21958
0
{
21959
0
    ImGuiContext& g = *GImGui;
21960
0
    ImGuiWindow* window = g.CurrentWindow;
21961
0
    ImGuiIDStackTool* tool = &g.DebugIDStackTool;
21962
21963
    // Step 0: stack query
21964
    // This assumes that the ID was computed with the current ID stack, which tends to be the case for our widget.
21965
0
    if (tool->StackLevel == -1)
21966
0
    {
21967
0
        tool->StackLevel++;
21968
0
        tool->Results.resize(window->IDStack.Size + 1, ImGuiStackLevelInfo());
21969
0
        for (int n = 0; n < window->IDStack.Size + 1; n++)
21970
0
            tool->Results[n].ID = (n < window->IDStack.Size) ? window->IDStack[n] : id;
21971
0
        return;
21972
0
    }
21973
21974
    // Step 1+: query for individual level
21975
0
    IM_ASSERT(tool->StackLevel >= 0);
21976
0
    if (tool->StackLevel != window->IDStack.Size)
21977
0
        return;
21978
0
    ImGuiStackLevelInfo* info = &tool->Results[tool->StackLevel];
21979
0
    IM_ASSERT(info->ID == id && info->QueryFrameCount > 0);
21980
21981
0
    switch (data_type)
21982
0
    {
21983
0
    case ImGuiDataType_S32:
21984
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%d", (int)(intptr_t)data_id);
21985
0
        break;
21986
0
    case ImGuiDataType_String:
21987
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%.*s", data_id_end ? (int)((const char*)data_id_end - (const char*)data_id) : (int)strlen((const char*)data_id), (const char*)data_id);
21988
0
        break;
21989
0
    case ImGuiDataType_Pointer:
21990
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "(void*)0x%p", data_id);
21991
0
        break;
21992
0
    case ImGuiDataType_ID:
21993
0
        if (info->Desc[0] != 0) // PushOverrideID() is often used to avoid hashing twice, which would lead to 2 calls to DebugHookIdInfo(). We prioritize the first one.
21994
0
            return;
21995
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "0x%08X [override]", id);
21996
0
        break;
21997
0
    default:
21998
0
        IM_ASSERT(0);
21999
0
    }
22000
0
    info->QuerySuccess = true;
22001
0
    info->DataType = data_type;
22002
0
}
22003
22004
static int StackToolFormatLevelInfo(ImGuiIDStackTool* tool, int n, bool format_for_ui, char* buf, size_t buf_size)
22005
0
{
22006
0
    ImGuiStackLevelInfo* info = &tool->Results[n];
22007
0
    ImGuiWindow* window = (info->Desc[0] == 0 && n == 0) ? ImGui::FindWindowByID(info->ID) : NULL;
22008
0
    if (window)                                                                 // Source: window name (because the root ID don't call GetID() and so doesn't get hooked)
22009
0
        return ImFormatString(buf, buf_size, format_for_ui ? "\"%s\" [window]" : "%s", window->Name);
22010
0
    if (info->QuerySuccess)                                                     // Source: GetID() hooks (prioritize over ItemInfo() because we frequently use patterns like: PushID(str), Button("") where they both have same id)
22011
0
        return ImFormatString(buf, buf_size, (format_for_ui && info->DataType == ImGuiDataType_String) ? "\"%s\"" : "%s", info->Desc);
22012
0
    if (tool->StackLevel < tool->Results.Size)                                  // Only start using fallback below when all queries are done, so during queries we don't flickering ??? markers.
22013
0
        return (*buf = 0);
22014
#ifdef IMGUI_ENABLE_TEST_ENGINE
22015
    if (const char* label = ImGuiTestEngine_FindItemDebugLabel(GImGui, info->ID))   // Source: ImGuiTestEngine's ItemInfo()
22016
        return ImFormatString(buf, buf_size, format_for_ui ? "??? \"%s\"" : "%s", label);
22017
#endif
22018
0
    return ImFormatString(buf, buf_size, "???");
22019
0
}
22020
22021
// ID Stack Tool: Display UI
22022
void ImGui::ShowIDStackToolWindow(bool* p_open)
22023
0
{
22024
0
    ImGuiContext& g = *GImGui;
22025
0
    if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize))
22026
0
        SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 8.0f), ImGuiCond_FirstUseEver);
22027
0
    if (!Begin("Dear ImGui ID Stack Tool", p_open) || GetCurrentWindow()->BeginCount > 1)
22028
0
    {
22029
0
        End();
22030
0
        return;
22031
0
    }
22032
22033
    // Display hovered/active status
22034
0
    ImGuiIDStackTool* tool = &g.DebugIDStackTool;
22035
0
    const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
22036
0
    const ImGuiID active_id = g.ActiveId;
22037
#ifdef IMGUI_ENABLE_TEST_ENGINE
22038
    Text("HoveredId: 0x%08X (\"%s\"), ActiveId:  0x%08X (\"%s\")", hovered_id, hovered_id ? ImGuiTestEngine_FindItemDebugLabel(&g, hovered_id) : "", active_id, active_id ? ImGuiTestEngine_FindItemDebugLabel(&g, active_id) : "");
22039
#else
22040
0
    Text("HoveredId: 0x%08X, ActiveId:  0x%08X", hovered_id, active_id);
22041
0
#endif
22042
0
    SameLine();
22043
0
    MetricsHelpMarker("Hover an item with the mouse to display elements of the ID Stack leading to the item's final ID.\nEach level of the stack correspond to a PushID() call.\nAll levels of the stack are hashed together to make the final ID of a widget (ID displayed at the bottom level of the stack).\nRead FAQ entry about the ID stack for details.");
22044
22045
    // CTRL+C to copy path
22046
0
    const float time_since_copy = (float)g.Time - tool->CopyToClipboardLastTime;
22047
0
    Checkbox("Ctrl+C: copy path to clipboard", &tool->CopyToClipboardOnCtrlC);
22048
0
    SameLine();
22049
0
    TextColored((time_since_copy >= 0.0f && time_since_copy < 0.75f && ImFmod(time_since_copy, 0.25f) < 0.25f * 0.5f) ? ImVec4(1.f, 1.f, 0.3f, 1.f) : ImVec4(), "*COPIED*");
22050
0
    if (tool->CopyToClipboardOnCtrlC && Shortcut(ImGuiMod_Ctrl | ImGuiKey_C, ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused))
22051
0
    {
22052
0
        tool->CopyToClipboardLastTime = (float)g.Time;
22053
0
        char* p = g.TempBuffer.Data;
22054
0
        char* p_end = p + g.TempBuffer.Size;
22055
0
        for (int stack_n = 0; stack_n < tool->Results.Size && p + 3 < p_end; stack_n++)
22056
0
        {
22057
0
            *p++ = '/';
22058
0
            char level_desc[256];
22059
0
            StackToolFormatLevelInfo(tool, stack_n, false, level_desc, IM_ARRAYSIZE(level_desc));
22060
0
            for (int n = 0; level_desc[n] && p + 2 < p_end; n++)
22061
0
            {
22062
0
                if (level_desc[n] == '/')
22063
0
                    *p++ = '\\';
22064
0
                *p++ = level_desc[n];
22065
0
            }
22066
0
        }
22067
0
        *p = '\0';
22068
0
        SetClipboardText(g.TempBuffer.Data);
22069
0
    }
22070
22071
    // Display decorated stack
22072
0
    tool->LastActiveFrame = g.FrameCount;
22073
0
    if (tool->Results.Size > 0 && BeginTable("##table", 3, ImGuiTableFlags_Borders))
22074
0
    {
22075
0
        const float id_width = CalcTextSize("0xDDDDDDDD").x;
22076
0
        TableSetupColumn("Seed", ImGuiTableColumnFlags_WidthFixed, id_width);
22077
0
        TableSetupColumn("PushID", ImGuiTableColumnFlags_WidthStretch);
22078
0
        TableSetupColumn("Result", ImGuiTableColumnFlags_WidthFixed, id_width);
22079
0
        TableHeadersRow();
22080
0
        for (int n = 0; n < tool->Results.Size; n++)
22081
0
        {
22082
0
            ImGuiStackLevelInfo* info = &tool->Results[n];
22083
0
            TableNextColumn();
22084
0
            Text("0x%08X", (n > 0) ? tool->Results[n - 1].ID : 0);
22085
0
            TableNextColumn();
22086
0
            StackToolFormatLevelInfo(tool, n, true, g.TempBuffer.Data, g.TempBuffer.Size);
22087
0
            TextUnformatted(g.TempBuffer.Data);
22088
0
            TableNextColumn();
22089
0
            Text("0x%08X", info->ID);
22090
0
            if (n == tool->Results.Size - 1)
22091
0
                TableSetBgColor(ImGuiTableBgTarget_CellBg, GetColorU32(ImGuiCol_Header));
22092
0
        }
22093
0
        EndTable();
22094
0
    }
22095
0
    End();
22096
0
}
22097
22098
#else
22099
22100
void ImGui::ShowMetricsWindow(bool*) {}
22101
void ImGui::ShowFontAtlas(ImFontAtlas*) {}
22102
void ImGui::DebugNodeColumns(ImGuiOldColumns*) {}
22103
void ImGui::DebugNodeDrawList(ImGuiWindow*, ImGuiViewportP*, const ImDrawList*, const char*) {}
22104
void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList*, const ImDrawList*, const ImDrawCmd*, bool, bool) {}
22105
void ImGui::DebugNodeFont(ImFont*) {}
22106
void ImGui::DebugNodeStorage(ImGuiStorage*, const char*) {}
22107
void ImGui::DebugNodeTabBar(ImGuiTabBar*, const char*) {}
22108
void ImGui::DebugNodeWindow(ImGuiWindow*, const char*) {}
22109
void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings*) {}
22110
void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>*, const char*) {}
22111
void ImGui::DebugNodeViewport(ImGuiViewportP*) {}
22112
22113
void ImGui::ShowDebugLogWindow(bool*) {}
22114
void ImGui::ShowIDStackToolWindow(bool*) {}
22115
void ImGui::DebugStartItemPicker() {}
22116
void ImGui::DebugHookIdInfo(ImGuiID, ImGuiDataType, const void*, const void*) {}
22117
22118
#endif // #ifndef IMGUI_DISABLE_DEBUG_TOOLS
22119
22120
//-----------------------------------------------------------------------------
22121
22122
// Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed.
22123
// Prefer just including imgui_internal.h from your code rather than using this define. If a declaration is missing from imgui_internal.h add it or request it on the github.
22124
#ifdef IMGUI_INCLUDE_IMGUI_USER_INL
22125
#include "imgui_user.inl"
22126
#endif
22127
22128
//-----------------------------------------------------------------------------
22129
22130
#endif // #ifndef IMGUI_DISABLE